Sadly as you've figured out there are no native intersection or union operations. It's not terribly complex to find the intersection though:
let a = new Set([1,2,3])
let b = new Set([1,2,4])
let intersect = new Set([...a].filter(i => b.has(i)));
console.log(...intersect)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Kit Sunde on Stack OverflowSadly as you've figured out there are no native intersection or union operations. It's not terribly complex to find the intersection though:
let a = new Set([1,2,3])
let b = new Set([1,2,4])
let intersect = new Set([...a].filter(i => b.has(i)));
console.log(...intersect)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
As of June 2024, Set has been added to the spec: you can use:
mySet.intersection(mySet2);
Show code snippet
const set1 = new Set([1, 2, 3]);
const set2 = new Set([1, 2, 4]);
const intersect = set1.intersection(set2);
console.log(...intersect);
<script src="https://unpkg.com/core-js-bundle@3.27.1/minified.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
It is live in Safari 17 and Chrome 122 and SerenityOS, and also supported in Node 22.
For other engines and backwards compatibility, you could use Immutable.js's Set, which inspired that proposal:
Immutable.Set(mySet).intersect(mySet2);
The point of sets is that they allow for two useful methods: union and intersection. ES6 sets only support union. Intersection is done using the .filter, so you might aswell just use plain old arrays and use some custom filter code for the union. Why!? Why!?