How to Add Array Values to an Existing JavaScript Set?

Add elements of an array to an existing Set in JavaScript

You can add elements of an array to an existing Set object in the following ways:

Using a Loop

If you have an existing Set that you want to add array elements to, then you can simply loop over the array and add each element to the Set (using the Set.prototype.add() method), for example, like so:

// ES6+
const arr = [1, 2, 3, 3, 4];
const existingSet = new Set();

existingSet.add(1);
existingSet.add(2);
existingSet.add(5);

arr.forEach((item) => existingSet.add(item));

console.log(existingSet); // Set(5) { 1, 2, 5, 3, 4 }

You can of course, use any other loop to iterate over the array as you want. Consider for example, as an alternative, using the for...of loop to do the same:

// ES6+
const arr = [1, 2, 3, 3, 4];
const existingSet = new Set();

existingSet.add(1);
existingSet.add(2);
existingSet.add(5);

for (const item of arr) {
    existingSet.add(item);
}

console.log(existingSet); // Set(5) { 1, 2, 5, 3, 4 }

Using the Set Constructor

Passing an iterable (such as an array) to a Set constructor adds all its elements to the new Set. If you merge the existing Set and array together, then you can simply pass the result to the Set constructor, for example, like so:

// ES6+
const arr = [1, 2, 3, 3, 4];
const existingSet = new Set();

existingSet.add(1);
existingSet.add(2);
existingSet.add(5);

const newSet = new Set([ ...existingSet, ...arr ]);

console.log(newSet); // Set(5) { 1, 2, 5, 3, 4 }

This works because you can use iterable objects (such as Set, array, etc.) with the spread syntax.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.