What is Set Intersection in JavaScript ?
Last Updated :
01 Feb, 2024
In JavaScript, the concept of Set intersection refers to finding the common elements between two or more sets. The result of the intersection operation is a new Set containing only the elements that are common to all the input sets.
Example: Here, The spread operator ([...set1]
) is used to convert the elements of set1
into an array. The filter()
method is applied to the array, retaining only the elements that are present in set2
using the has()
method.
Javascript
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6]);
const intersection = new Set([...set1]
.filter(element => set2.has(element)));
console.log(intersection);
|
Share your thoughts in the comments
Please Login to comment...