Add Array of Values to an Existing Set in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

Add Array of Values to an Existing Set #

To add an array of values to an existing Set:

  1. Use the forEach() method to iterate over the array.
  2. On each iteration use the add() method to add the array element to the Set.
  3. After the last iteration, all values from the array will be added to the Set.
index.js
const set1 = new Set(); const arr = ['one', 'two', 'three']; arr.forEach(element => { set1.add(element); }); console.log(set1); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three'}

The function we passed to the Array.forEach method gets called with each element in the array.

On each iteration, we use the Set.add method to add the element to the Set.

Note that Set objects store only unique values. If your array contains duplicates, none of the duplicates would get added to the Set.

index.js
const set1 = new Set(); const arr = ['one', 'one', 'one']; arr.forEach(element => { set1.add(element); }); console.log(set1); // ๐Ÿ‘‰๏ธ {'one'}

Our array contains 3 elements, but there are 2 duplicates, which did not get added to the Set object.

An alternative approach is to use the spread syntax (...).

To add an array of values to an existing Set:

  1. Create a new Set using the Set() constructor.
  2. Use the spread operator to unpack the values of the Set and the array into the new Set, e.g. new Set([...set, ...arr]).
  3. The new Set will contain the values from the original Set and the array.
index.js
const set1 = new Set(); const arr = ['one', 'two', 'three']; const newSet = new Set([...set1, ...arr]); console.log(newSet); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three'}

We created a new Set using the Set() constructor, in which we unpacked the values of the original Set and the values of the array.

Both Set`s and arrays are iterable objects, so we are able to use the spread operator (...) to unpack their values into a new `Set`.

This approach is quite clean and compact, however it doesn't add values to the original Set, it creates a new Set.

If you want to add the array's values to the original Set, use the forEach approach.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee