Borislav Hadzhiev
Sun Oct 17 2021·1 min read
Photo by Eldar Nazarov
To get the intersection of two arrays:
Set
objects to remove any of the duplicates.Set
back to an array and call the filter()
method on
it.Set
.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.
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.