0 day streak
javascript / intermediate
Snippet

Set Intersection for Data Deduplication

Using the Set object's has() method inside a filter provides a highly performant way to find the intersection of two arrays. Set lookup is O(1) complexity compared to O(n) for Array.includes().

snippet.js
javascript
1
2
3
4
5
const groupA = [1, 2, 3, 4];
const groupB = [3, 4, 5, 6];
const setB = new Set(groupB);
const intersection = groupA.filter(item => setB.has(item));
console.log(intersection); // [3, 4]
Breakdown
1
const setB = new Set(groupB);
Converts the second array to a Set for O(1) lookup performance.
2
groupA.filter(item => setB.has(item));
Iterates through the first array and keeps items present in the Set.