Skip to content

JavaScript Set add multiple | Example

  • by

Using a loop you can add multiple values to a JavaScript Set. You can simply loop over the array and add each element to the Set (using add() method).

JavaScript Set adds multiple

Simple example code using for each to add array values into a set.

<!DOCTYPE html>
<html>
<body>
  <script>
   const arr = [1, 2, 3, 3, 4];
   const set1 = new Set();

   console.log(set1)

   arr.forEach((item) => set1.add(item));
   console.log(set1); 

 </script>
</body>
</html>

Output:

JavaScript Set add multiple

Alternative, using the for...of loop to do the same:

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

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

If you merge the existing Set and array together, then you can simply pass the result to the Set constructor, for example, like so:

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

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

Do comment if you have any doubts or suggestions on this Js set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading