JavaScript - Set.intersection() Method
The Set.intersection() method in JavaScript takes another set object as a parameter and returns a new set object containing elements that are common to both the original Set and the provided Set.
To get a better understanding, let us assume there are two sets ("set1" and "set2"), if "set1" is the original set and "set2" is passed to the intersection() method, it returns a new set containing elements that are present in both set1 and set2.
Note − At the moment, this method has only limted availability. It only works in safari.
Syntax
Following is the syntax of JavaScript Set.intersection() method −
intersection(other)
Parameters
This method accepts the following parameter −
- other − A Set object.
Return value
This method returns a new set object containing elements in both this set and the other set.
Examples
Example 1
In the following example, we are using the JavaScript Set.intersection() method return the common elements in both the sets.
<html>
<body>
<script>
const set1 = new Set([10, 20, 40, 60, 70]);
const set2 = new Set([10, 40, 90]);
document.write(set1.intersection(set2));
</script>
</body>
</html>
If we execute the above program, it returns a new set objects containing {10, 40} as elements.
Example 2
If one of either set is empty, this method returns empty set object as result.
<html>
<body>
<script>
const set1 = new Set([]);
const set2 = new Set([]);
document.write(set1.intersection(set2));
</script>
</body>
</html>
After executing the above program, it will return empty set object as result.