how to get the union of two sets in javascript

To get the union of two sets in JavaScript, you can use the Set object and the spread operator. Here's an example:

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

In this example, we create two sets (set1 and set2) and use the spread operator to create a new set (union) that contains all the unique elements from both sets. Finally, we log the union set to the console.

Note that the Set object is available in modern browsers and Node.js, but may not be available in older browsers. You can use a polyfill or a library like Lodash to provide fallbacks for older browsers.

related categories

gistlibby LogSnag