Get the Intersection of two Arrays in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 17, 2021

banner

Photo from Unsplash

Get the Intersection of two Arrays #

To get the intersection of two arrays:

  1. Convert the arrays into Set objects to remove any of the duplicates.
  2. Convert the first Set back to an array and call the filter() method on it.
  3. On each iteration check if the current element is contained in the second Set.
index.js
function getIntersection(a, b) { const set1 = new Set(a); const set2 = new Set(b); const intersection = [...set1].filter( element => set2.has(element) ); return intersection; } const arr1 = ['a', 'b', 'c', 'c']; const arr2 = ['a', 'b', 'c', 'd', 'e', 'a']; // 👇️ ['a', 'b','c'] console.log(getIntersection(arr1, arr2));

We used the Set object to remove all the duplicates from the two arrays.

The Set object only stores unique values.

We did this because we don't want our intersection to contain duplicate values, e.g. ['a', 'b', 'c', 'c'].

Then we used the spread operator (...) to convert the Set back into an array, on which we called the filter method.

The function we passed to the Array.filter method gets called with each element in the array.

On each iteration we check if the element is contained in the second Set.

The filter method returns an array containing the elements, for which the test function returns a truthy value.

In our case, these are all the elements that are contained in both arrays.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.