Skip to content

Add array to Set JavaScript

  • by

Use forEach to Add an array to Set in JavaScript. If you have an existing Set that you want to add array elements, then you can simply loop over the array and add each element to the Set.

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

Add array to Set JavaScript

Simple example code.

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

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

    console.log(set1); 
  </script>
</body>
</html>

Output:

Add array to Set JavaScript

While Set API is still very minimalistic, you can use Array.prototype.forEach and shorten your code a bit:

array.forEach(item => mySet.add(item))

You can also use Array.reduce():

const mySet = new Set();
mySet.add(42); // Just to illustrate that an existing Set is used

[1, 2, 3].reduce((s, e) => s.add(e), mySet);

Do comment if you have any doubts or suggestions on this Js array 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