Compute intersection of two arrays in JavaScript [duplicate]

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.

Leave a Comment