how to get the intersection of two sets in typescript

To get the intersection of two sets in TypeScript, we can convert them to arrays and then use the filter() method together with the has() method of the Set object.

index.ts
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);

const intersection = [...set1].filter(x => set2.has(x));

console.log(intersection); // Output: [2, 3]
170 chars
7 lines

In the code above, we first create two Set objects and then convert them to arrays using the spread operator .... We then use the filter() method to create a new array that contains only the elements that are present in both sets. The has() method is called on the second set (set2) to check if each element of the first set (set1) is also present in the second set.

Finally, we log the intersection array to the console, which contains the values 2 and 3 (since these are the only values that are present in both sets).

gistlibby LogSnag