Introduction
JavaScript now has support for Set methods in multiple environments:
Safari 17 on 2023/09/18, Chrome122 on 2024/02/21 and Firefox127 on 2024/06/11 implemented it, making set operations available in all major browsers. It has successfully reached Stage 4, or up, as ES2025.
What is it?
intersection
new Set([1, 2, 3, 4]).intersection( new Set([1, 3, 5])); // Set{1, 3}
new Set([1, 2, 3, 4]).intersection( new Set([5, 6, 7])); // Set{}
It is the so-called AND.
union
new Set([1, 2, 3]).union( new Set([1, 3, 5])); // Set{1, 2, 3, 5}
new Set([1, 2, 3]).union( new Set([4, 5, 6])); // Set{1, 2, 3, 4, 5, 6}
It is the so-called OR.
difference
new Set([1, 2, 3]).difference( new Set([1, 3, 5])); // Set{2}
new Set([1, 2, 3]).difference( new Set([4, 5, 6])); // Set{1, 2, 3}
symmetricDifference
new Set([1, 2, 3]).symmetricDifference( new Set([1, 3, 5])); // Set{2, 5}
new Set([1, 2, 3]).symmetricDifference( new Set([4, 5, 6])); // Set{1, 2, 3, 4, 5, 6}
It is the so-called XOR.
isSubsetOf
Returns true if all elements are included in the argument.
new Set([1, 2, 3]).isSubsetOf( new Set([1, 2, 3, 4])); // true
new Set([1, 2, 3]).isSubsetOf( new Set([1, 2, 4, 5])); // false
new Set([1, 2, 3]).isSubsetOf( new Set([1, 2, 3])); // true
new Set().isSubsetOf( new Set([1, 2, 3])); // true
It is also true if the element is an empty set or A==B.
isSupersetOf
Returns true if the argument is contained in an element.
new Set([1, 2, 3]).isSupersetOf( new Set([1, 2, 3, 4])); // false
new Set([1, 2, 3]).isSupersetOf( new Set([1, 2, 4, 5])); // false
new Set([1, 2, 3]).isSupersetOf( new Set([1, 2, 3])); // true
new Set([1, 2, 3]).isSupersetOf( new Set()); // true
isDisjointFrom
Returns true if the elements and arguments have nothing in common.
new Set([1, 2, 3]).isDisjointFrom(new Set([4, 5, 6])); // true
new Set([1, 2, 3]).isDisjointFrom(new Set([2, 5, 6])); // false
new Set([]).isDisjointFrom(new Set([])); // true
Conclusion
These functions have been available to the public through polyfill for a long time.
Each of these functions is less than 10 lines long, and the self-implementation of the set operation itself is not difficult at all.
Top comments (0)