How to Convert a Set to an Array in JavaScript?

A set in JavaScript is almost similar to an array. The only difference is that a value in a set can occur only once i.e. it is unique in the entire set. But, in an array, a value can appear once or more.

So, if you want to convert a set to an array, you can use the built-in method Array.from(). The Array.from() method takes in a single parameter which can be any iterable object such as a string, set, map, etc. and returns a new shallow copied array.

// Create a new set of numbers
const set = new Set([1, 2, 3, 4, 5]);

// Convert set to array
const arr = Array.from(set);

console.log(arr);
// Output: [1, 2, 3, 4, 5]

Convert a Set to an Array using the Spread Operator(…)

You can also use the spread operator to convert a set to an array. The spread operator was introduced in ES6 specification of JavaScript.

The spread operator is represented by three dots(...). It allows us to unpack values from an iterable such as a string, set, map, array, etc.

The following code converts the set to an array by unpacking its values:

// Create a new set of numbers
const set = new Set([1, 2, 3, 4, 5]);

// Convert set to array
const arr = [...set];

console.log(arr);
// Output: [1, 2, 3, 4, 5]

You could also convert multiple sets into a single array with the spread syntax. You just need to separate these sets with commas.

See the following example:

// Create new sets
const set1 = new Set([1, 2, 3, 4, 5]);
const set2 = new Set([6, 7, 8, 9, 10]);

// Convert sets to array
const arr = [...set1, ...set2];

console.log(arr);
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Convert a Set to an Array using the forEach Loop

Another solution could be to create an empty array and then one by one push each set item into this array. To get each item of the set one by one you can use a forEach or for loop.

See the following example:

// Create a new set
const set = new Set([1, 2, 3, 4, 5]);

// Create empty array
const arr = [];

// Push each set item to array
set.forEach(value=>{
    arr.push(value);
});

console.log(arr);
// Output: [1, 2, 3, 4, 5]

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.