javascriptset

How to add an array of values to a Set


The old school way of adding all values of an array into the Set is:

// for the sake of this example imagine this set was created somewhere else 
// and I cannot construct a new one out of an array
let mySet = new Set()

for(let item of array) {
  mySet.add(item)
}

Is there a more elegant way of doing this? Maybe mySet.add(array) or mySet.add(...array)?

PS: I know both do not work


Solution

  • As of June 2024, the new Set methods are considered baseline, as they are now available on all major browsers, plus Node.js, Deno, and Bun.

    This means that now there is a way that can be considered elegant, as well as functional, by using the Set.prototype.union() method:

    const set = new Set(['a', 'b', 'c'])
    const arr = ['d', 'e', 'f']
    const extendedSet = set.union(new Set(arr));
    // Set { 'a', 'b', 'c', 'd', 'e', 'f' }
    

    It works by creating a Set from the array and then creating a new Set which is the union of the two (i.e. it contains elements which are in either or both of the initial Set and the Set created from the array).