The JavaScript Set methods are now part of Baseline  |  Blog  |  web.dev

You can now use the JavaScript Set
methods

to perform set operations like
intersection,
union
and more.

Sets are an essential data structure in any programming language. Now you can
use JavaScript’s built-in methods to perform set operations. Simplify your set
operations using the following methods:

intersection()

intersection()
returns a new set containing elements in both this set and the given set.

const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.intersection(squares)); // Set(2) { 1, 9 }

union()

union()
returns a new set containing all elements in this set and the given set.

const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 }

difference()

difference()
returns a new set containing elements in this set but not in the given set.

const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.difference(squares)); // Set(3) { 3, 5, 7 }

symmetricDifference()

symmetricDifference()
returns a new set containing elements that are in either this set or the given
set, but not in both.

const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.symmetricDifference(squares)); // Set(5) { 2, 6, 8, 1, 9 }

isSubsetOf()

isSubsetOf()
returns a boolean indicating if all elements of this set are in the given set.

const fours = new Set([4, 8, 12, 16]);
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(fours.isSubsetOf(evens)); // true

isSupersetOf()

isSupersetOf()
returns a boolean indicating if all elements of the given set are in this set.

const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
const fours = new Set([4, 8, 12, 16]);
console.log(evens.isSupersetOf(fours)); // true

isDisjointFrom()

isDisjointFrom()
Returns a boolean indicating if this set has no elements in common with the
given set.

const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const squares = new Set([1, 4, 9, 16]);
console.log(primes.isDisjointFrom(squares)); // true

Updating your code to use the built-in methods improves performance and reduces
technical debt.