How To Add Array Of Values To An Existing Set In JavaScript

Add Array of Values to an Existing Set in JavaScript

Set is an object that is popular with users when learning about JS. In this article, I will show you how to add array of values to an existing Set in JavaScript. Now let’s find out the methods.

The Set object in JavaScript

Set object is a set of non-key and non-duplicating values. So the set of values ​​will be unique.

You can add elements to a Set object using the add() method.

Code sample

// Instantiate a new Set object
let set = new Set(["two", "three", "ten", "one"]);

// Add a new element
set.add("two");
set.add("five");
console.log(set);

Output

{'two', 'three', 'ten', 'one', 'five'}

In this example, you can see duplicate values ​​are added to a Set object. After that the duplicate values ​​are removed in Set.

Add array of values to an existing Set in JavaScript

Using forEach() method or for…of loop 

You can add each array element to the Set object by traversing the elements in the array using a for...of loop or the forEach() method. The elements of the array will be traversed in order and added to the Set object.

Code sample

let set = new Set();
let array1 = ["one", "two", "three", "one"];
let array2 = ["1", "2", "3", "4"];

// Add each element by forEach() method
array1.forEach((element) => {
	set.add(element);
});

console.log(set);

// Similar to for...of loop
for (const element of array2) {
	set.add(element);
}

console.log(set);

Output

{'one', 'two', 'three'}
{'one', 'two', 'three', '1', '2', '3', '4'}

Using the spear operator (…)

The JavaScript spread operator (...) copies all or part of an existing object or array into another object or array. 

The spread syntax: ellipsis (...) is used in function calls (Or in arrays, objects) and can be placed anywhere in the list of parameters.

Used to split arrays into a list of parameters passed to the function or concatenate/copy arrays, concatenate/copy objects.

Code sample

let set = new Set();
let array1 = ["one", "two", "three", "one"];
let array2 = ["1", "2", "3", "4"];

// The JavaScript spread operator (...)
set = new Set([...array1, ...array2]);
console.log(set);

Output

{'one', 'two', 'three', '1', '2', '3', '4'}

Summary

In conclusion, I’ve shown you how to add array of values to an existing Set in JavaScript by many methods. The JavaScript spread operator (...) method is simple and fast, so you can easily apply it. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *