Simplest code for array intersection in javascript

Peter picture Peter · Dec 11, 2009 · Viewed 430.3k times · Source

What's the simplest, library-free code for implementing array intersections in javascript? I want to write

intersection([1,2,3], [2,3,4,5])

and get

[2, 3]

Answer

Anon. picture Anon. · Dec 11, 2009

Use a combination of Array.prototype.filter and Array.prototype.includes:

array1.filter(value => array2.includes(value))

For older browsers, with Array.prototype.indexOf and without an arrow function:

array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
})