To find the intersection of two sets in TypeScript, you can use the Set object and the filter method.
In this example,
set1
and set2
.filter
method on set1
to keep only the elements that are present in set2
.let set1 = new Set([1, 2, 3, 4, 5]);
let set2 = new Set([4, 5, 6, 7, 8]);
let intersection = new Set([...set1].filter(x => set2.has(x)));
console.log('Intersection:', intersection);
Intersection: Set(2) { 4, 5 }
In this example,
set1
and set2
.set1
using a for...of
loop and add elements that are present in set2
to a new set named intersection
.let set1 = new Set([1, 2, 3, 4, 5]);
let set2 = new Set([4, 5, 6, 7, 8]);
let intersection = new Set();
for (let item of set1) {
if (set2.has(item)) {
intersection.add(item);
}
}
console.log('Intersection:', intersection);
Intersection: Set(2) { 4, 5 }
In this tutorial, we learned How to find Intersection of Two Sets in TypeScript language with well detailed examples.