3
103

JavaScript: How to Convert Set to Array

Reading Time: 2 minutes

To convert Set to Array in JavaScript, there are 3 main methods that are 1 or 2 liner code. There will return an array in the same order during the creation of Set.

Methods to Convert Set to Array

  • Array.from() Method
  • Array.prototype.forEach() Method
  • Spread Operator/Syntax (...) Method

Array.from() Method

Array.from() is a static method that will create a new array shallow copying the objects from any iterable objects including Set. This method is good if the all datatype are primitive datatype.

In the example below, by passing in the Set object, it will return a new array containing all element in the same order.

const mySet = new Set(['Person1', 101, false, 'Person 2']);

const result = Array.from(mySet);

console.log(result);
// ["Person1", 101, false, "Person 2"]

Array.prototype.forEach() Method

From this guide, we know that forEach() will not return any result. Hence, we will create a new array before executing the method.

In the example below, we will push the data in every iteration to the result array.

const mySet = new Set(['Person1', 101, false, 'Person 2']);

const result = [];
mySet.forEach(data => result.push(data));

console.log(result);
// ["Person1", 101, false, "Person 2"]

Spread Operator/Syntax (...) Method

Base on the official documentation of Spread Syntax, we can see that it can expand ant iterable. Thus, we can make use of its mechanism to spread out into an array object.

In the example below, we spread the Set iterable object into an array.

const mySet = new Set(['Person1', 101, false, 'Person 2']);

const result = [...mySet];

console.log(result);
// ["Person1", 101, false, "Person 2"]

Conclusion

We look into the 3 methods of converting set to array in JavaScript.

Array.from() and the spread operator are the easiest to implement the datatype inside the Set are all primitive type. Array.prototype.forEach() method will be good if you want to perform some operation like deep cloning.

Show Comments

No Responses Yet

Leave a Reply