how to get the union of two sets in typescript

To get the union of two sets in TypeScript, we can use the spread operator (...) to convert the sets to arrays and then use the Set constructor to remove duplicates. Here's an example:

index.ts
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const unionSet = new Set([...set1, ...set2]);
console.log(unionSet); // Set {1, 2, 3, 4}
155 chars
5 lines

In this example, we first create two sets set1 and set2. Then we use the spread operator to convert each of them into an array and concatenate them into a single array. We then create a new set unionSet from this concatenated array using the Set constructor. The Set constructor automatically removes any duplicated values, giving us the union of the two sets.

Note that the spread operator only works with arrays, so we need to convert the sets to arrays before we can use it.

gistlibby LogSnag