JavaScript

JavaScript: Set Data Structure: Intersect

A JavaScript Set is a set of distinct values. In a Set, each value can only appear once. A Set can hold any data type’s value. More specifically, Intersection (A ∩ B) generates a set containing the members of the first set “A” that also exist in the second set “B”.

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 setA = new Set([1, 5, 3, 9, 11]);
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:
function setsIntersection(set1, set2) {
 const intersection = new Set([...set1].filter(element => set2.has(element)));
 return intersection;
}

Call the defined function by passing sets as arguments:

console.log(setsIntersection(setA, setB));

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:

for(var x of setA) {
 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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.