To convert a set to array in JavaScript we simply need to pass the set as a parameter in the JavaScript Array.from method.

var numbers_set = new Set([11, 48, 101, 15, 41, 3, 13, 92]);
var numbers_array = Array.from(numbers_set);

console.log(numbers_array);

#Output:
[11, 48, 101, 15, 41, 3, 13, 92]

Let’s take a look at another example of this below.


Let’s say we have a simple set of colors and we want to convert the set to an array. To do this we simply use the Array.from() method again, passing it the set of colors.


var color_set = new Set(["red","blue","green","red","yellow","orange","black","purple","pink","blue","black"]);
var arrayOfColors = Array.from(color_set);

console.log(arrayOfColors);

In this example, the resulting array, arrayOfColors, would now contain the following:

[‘red’, ‘blue’, ‘green’, ‘yellow’, ‘orange’, ‘black’, ‘purple’, ‘pink’]

Converting a Set to Array Using the JavaScript forEach() Method

We can also convert a set to an array by using the JavaScript forEach() method. The forEach() method will simply go through all of the items in the set, which we will then add to a new array using the push() method.


var someSet = new Set(["somestring",true,{name: "Tom", age: "47"}, 457, "This is a string of text"]);

var setToArray = [];

someSet.forEach(function (eachItem) {
  setToArray.push(eachItem);
});

console.log(setToArray);

#Output
['somestring', true, {name: 'Tom', age: '47'}, 457, 'This is a string of text']

Hopefully this article has been useful to help you understand how to convert a set to array JavaScript.

Categorized in:

JavaScript,

Last Update: March 22, 2024