Borislav Hadzhiev
Thu Oct 28 2021·2 min read
Photo by Rodion Kutsaev
To add an array of values to an existing Set
:
forEach()
method to iterate over the array.add()
method to add the array element to the
Set
.Set
.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
.
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
:
Set
using the Set()
constructor.Set
and the array into
the new Set
, e.g. new Set([...set, ...arr])
.Set
will contain the values from the original Set
and the array.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.
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.