This post will define the intersection of sets in JavaScript.
How to Intersect the JavaScript Set Data Structure?
To get the intersection of two sets, use the below-mentioned methods:
- filter() method with has() method
- for loop
Method 1: Intersection of Two Sets Using filter() Method With has() Method
To get the intersection of the two sets, use the “filter()” method with “has()” method. The filter() method filters the elements from “sets” by iterating over the sets. Whereas has() method checks whether the element exists/included in the set.
Example
First, create two sets, “setA” and “setB” using “Set()” constructor:
var setB = new Set([11, 18, 12, 26, 5]);
Define a function “setsIntersection” by passing two sets as parameters:
- Use the spread operator to convert the set into an array and then call the filter method on it.
- The callback function of the filter() method calls the has() method, which determines whether or not the value is included in the second Set.
- filter() method outputs an array that contains values in both sets.
- Finally, call the Set() constructor for converting the returned array to a set:
const intersection = new Set([...set1].filter(element => set2.has(element)));
return intersection;
}
Call the defined function by passing sets as arguments:
As you can see, 5 and 11 is the only common digits in setA and setB:
Method 2: Intersection of Two Sets Using for Loop
The most common and traditional method is to use the “for” loop.
Example
Here, we will check whether the element of setA is present in the setB using the has() method. If the element of setA is found in setB, add them in a new Set using the “add()” method:
if(setB.has(x)) {
setsIntersection.add(x);
}
Output
That’s all about the intersection of the JavaScript Sets intersection.
Conclusion
To get the intersection of two sets, use the “filter()” method with the “has()” method or the “for” loop. In both approaches, the has() method is the main key to getting the intersection. The has() method verifies whether the specified element exists in the Set or not. This post defined the intersection of sets in JavaScript.