How to Get the Intersection of Two Arrays in JavaScript


I recently needed the intersection of two arrays in my JavaScript code.

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5]
const res = intersection(arr1, arr2);
console.log(res); // [2, 3, 4]

Using filter()

We can filter the first array with only values that appear in the second array.

function intersection(arr1, arr2) {
  return arr1.filter(elem => arr2.includes(elem));
}

Using Sets

We can use a similar technique, but speed up the includes() lookup times using a set.

function intersection(arr1, arr2) {
  const set = new Set(arr2);
  const intersection = new Set(arr1.filter(elem => set.has(elem)));
  return Array.from(intersection);
}

The includes() array method searches every element in the array, which means it is a O(n) operation.

The has() set method returns an answer in constant time, so it is arguably more efficient. However, the entire process does require two extra O(n) operations (converting to a set and converting back to an array).