HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Simplest code for array intersection in javascript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayintersectionforjavascriptcodesimplest

Problem

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]

Solution

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

const filteredArray = array1.filter(value => array2.includes(value));


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

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


NB! Both .includes and .indexOf internally compares elements in the array by using ===, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead.

Code Snippets

const filteredArray = array1.filter(value => array2.includes(value));
var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

Context

Stack Overflow Q#1885557, score: 1957

Revisions (0)

No revisions yet.