how to get the intersection of two sets in javascript

To get the intersection of two sets in JavaScript, you can use the built-in Set data structure and the filter method along with the has method of a Set. Here's an example:

index.tsx
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

const intersection = new Set([...setA].filter(x => setB.has(x)));

console.log(intersection); // Set { 3, 4 }
183 chars
7 lines

In this example, we create two sets setA and setB. We then use the filter method on the setA set, and for each element in setA, we check if the setB set has that element using the has method. If setB has the element, we keep it in the resulting set intersection.

Finally, we convert the resulting set back into an array for further usage if needed.

gistlibby LogSnag