Simplest code for array intersection in JavaScript?

Array intersection finds common elements between two or more arrays. In JavaScript, the simplest approach uses filter() combined with includes().

Basic Example

Let's find common elements between two arrays:

var firstNamesArray = ["John", "David", "Bob", "Sam", "Carol"];
var secondNamesArray = ["Mike", "Carol", "Adam", "David"];

var intersectionOfArray = firstNamesArray.filter(v => 
    secondNamesArray.includes(v));

console.log("Intersection of two arrays:");
console.log(intersectionOfArray);
Intersection of two arrays:
[ 'David', 'Carol' ]

How It Works

The filter() method creates a new array with elements that pass the test. For each element in the first array, includes() checks if it exists in the second array:

// Step by step breakdown
var arr1 = ["a", "b", "c"];
var arr2 = ["b", "c", "d"];

// Check each element of arr1
console.log(arr2.includes("a")); // false
console.log(arr2.includes("b")); // true
console.log(arr2.includes("c")); // true

var result = arr1.filter(item => arr2.includes(item));
console.log("Common elements:", result);
false
true
true
Common elements: [ 'b', 'c' ]

Using Set for Better Performance

For larger arrays, converting to a Set improves performance since Set lookup is O(1):

var numbers1 = [1, 2, 3, 4, 5];
var numbers2 = [3, 4, 5, 6, 7];

var set2 = new Set(numbers2);
var intersection = numbers1.filter(x => set2.has(x));

console.log("Intersection using Set:", intersection);
Intersection using Set: [ 3, 4, 5 ]

Multiple Arrays Intersection

To find intersection of multiple arrays, use reduce():

var arrays = [
    [1, 2, 3, 4],
    [2, 3, 4, 5],
    [3, 4, 5, 6]
];

var intersection = arrays.reduce((acc, current) => 
    acc.filter(x => current.includes(x)));

console.log("Multiple arrays intersection:", intersection);
Multiple arrays intersection: [ 3, 4 ]

Comparison

Method Performance Use Case
filter() + includes() O(n×m) Small arrays, simple code
filter() + Set.has() O(n+m) Large arrays, better performance

Conclusion

Use filter() with includes() for simple array intersection. For better performance with large datasets, convert one array to a Set and use has() method.

Updated on: 2026-03-15T23:18:59+05:30

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements