In This article, we will learn javascript set intersection with 2 different methods.
what is an Intersection?
In mathematical terms, this is expressed as an Intersection A ∩ B creates a set that contains those elements of a set A that is also in the set B. in simple words Intersection means elements common in both “A” and “B”.
Step to get the intersection of Sets
- Convert the first
Set
into an array. - Use the
filter()
method to iterate over the array. - Use the
has()
method to check if each value is contained in the secondSet
. - Convert the array back to a
Set
.
Method 1: JavaScript Set intersection
let a = new Set([1,2,3]);
let b = new Set([4,3,2]);
let intersection = new Set(
[...a].filter(x => b.has(x))
);
console.log(intersection); // Output: { 2, 3 }
Explanation:
Here We used the ES6 spread syntax (…) to convert the first Set to an array.
console.log([...a]); // [ 1, 2, 3 ]
After we use the filter()
method to iterate over the array. On each iteration.
The filter() method creates a new array with satisfying the provided condition
we call the Set.has method to check if the value is contained in the second Set
.
The has()
method returns true
if the value is found in the Set
, and false
otherwise.
In last we use Set() constructor to convert the array back to a Set
.
Method 2: JavaScript Set intersection
Here you can also achieve the same thing using a loop over one of the Set objects, and check which elements are common between the two by using the has() method on the other Set. For example:
const setA = new Set([1, 2, 3]);
const setB = new Set([4, 3, 2, 6]);
const result = new Set();
for (const elem of setA) {
if (setB.has(elem)) {
result.add(elem);
}
}
console.log(result); // Set(2) {2, 3}