Compute intersection of two arrays in JavaScript [duplicate]

Given two arrays of unequal length:

var arr1 = ["mike", "sue", "tom", "kathy", "henry"]; //arr1.length = 5
var arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"]; //arr2.length = 7

How can I find the values common to both arrays? In this case "sue" and "kathy" should be returned.


Here is an intersection function based on Array.prototype.filter

function intersect(a, b) {
    var t;
    if (b.length > a.length) t = b, b = a, a = t; // indexOf to loop over shorter
    return a.filter(function (e) {
        return b.indexOf(e) > -1;
    });
}

var arr1 = ["mike", "sue", "tom", "kathy", "henry"];
    arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

intersect(arr1, arr2); // ["sue", "kathy"]

You might also want to consider the following

var arr1 = ['sue', 'sue', 'kathy'],
    arr2 = ['kathy', 'kathy', 'sue'];

The above would now give ["sue", "sue", "kathy"]. If you don't want duplicates you could do a further filter on this. This would also standardise results. i.e.

return a
    .filter(/* .. */) // same as before
    .filter(function (e, i, c) { // extra step to remove duplicates
        return c.indexOf(e) === i;
    });

Adding this will now return the same result as the previous arrays (["sue", "kathy"]), even though there were duplicates.


You could use Array.filter:

var result = arr1.filter(function(n) {
  return arr2.indexOf(n) > -1;
});

You want to find the intersection of two arrays?

You could use Underscore's intersection(). This will give you a list of values present in both arrays.

var commonValues = _.intersection(arr1, arr2);

jsFiddle.

If you didn't want to use a library, it'd be trivial to implement...

var commonValues = arr1.filter(function(value) { 
                                   return arr2.indexOf(value) > -1;
                               });

jsFiddle.

If Array.prototype.filter() and Array.prototype.indexOf() are not supported in your target platforms...

var commonValues = [];
var i, j;
var arr1Length = arr1.length;
var arr2Length = arr2.length;

for (i = 0; i < arr1Length; i++) {
    for (j = 0; j < arr2Length; j++) {
        if (arr1[i] === arr2[j]) {
            commonValues.push(arr1[i]);
        }
    }
}

jsFiddle.


Iterate over one of the arrays and compare the objects with the other:

var results = [];

for (var i = 0; i < arr1.length; i++) {
    if (arr2.indexOf(arr1[i]) !== -1) {
        results.push(arr1[i]);
    }
}