How to Convert Set to Array in JavaScript

Here are three ways to convert a Set to an Array in JavaScript:

  1. Using Array.prototype.from()
  2. Using Array.prototype.forEach()
  3. Using spread operator

Method 1: Using Array.prototype.from()

JavaScript Array.from() method is “used to create a new, shallow-copied Array instance from an array-like or iterable object like Set.”

Let’s see how to use an array.from() method:

const ourSet = new Set(["Iron", "Thor", "strange", "captain"]);
const setToArray = Array.from(ourSet);

console.log("Our Set : ", ourSet);
console.log("Set To Array : ", setToArray);

Output

Our Set : Set(4) { 'Iron', 'Thor', 'strange', 'captain' }
Set To Array : [ 'Iron', 'Thor', 'strange', 'captain' ]

Method 2: Using Array.prototype.forEach()

Create an empty array first and then iterate the Set elements using the forEach() method and push one element at a time to the empty Array; that way, in that end, you will get a new array.

const ourSet = new Set(["Iron", "Thor", "strange", "captain"]);
const array = [];

ourSet.forEach((value) => {
 array.push(value);
})

console.log("Our Set : ", ourSet);
console.log("Set To Array : ", array);

Output

Our Set : Set(4) { 'Iron', 'Thor', 'strange', 'captain' }
Set To Array : [ 'Iron', 'Thor', 'strange', 'captain' ]

Method 3: Using the spread operator

Spread Operator iterates each element in the set and returns that element. It creates a shallow copy.

const ourSet = new Set(["hello", "how", "fine", "good"]);
const array = [...ourSet];

console.log("Our Set : ", ourSet);
console.log("Set To Array : ", array);

Output

Our Set : Set(4) { 'hello', 'how', 'fine', 'good' }
Set To Array : [ 'hello', 'how', 'fine', 'good' ]

That’s it!