symdesign
2/6/2016 - 11:09 AM

Find array intersections

Function that finds the intersection of two arrays based on Array.prototype.filter: http://stackoverflow.com/questions/16227197/compute-intersection-of-two-arrays-in-javascript Plus function that finds the difference of two arrays based on Array.prototype.filter: http://stackoverflow.com/questions/1187518/javascript-array-difference compatible from IE 9 (http://caniuse.com/#search=ECMAScript%205)

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

////////////////////  
// Examples  
////////////////////

[1,2,3,4,5,6].diff( [3,4,5] );  
// => [1, 2, 6]

["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);  
// => ["test5", "test6"]
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) {
            if (b.indexOf(e) !== -1) return true;
        })
        .filter(function (e, i, c) { // extra step to remove duplicates
            return c.indexOf(e) === i;
        });
}