Course contentsShow
← JavaScript
Lesson 1052 of 2,72324. Maps and SetsFree lesson

Converting Sets to Arrays

Use spread syntax and Array.from() to convert Sets into arrays for further processing.

Converting Sets to Arrays

What you'll learn: How to transform a Set into a standard array so you can use array methods like map(), filter(), and reduce().

While Sets are great for ensuring uniqueness and fast membership checks, sometimes you need the full power of array methods for further processing. Fortunately, JavaScript gives you two simple ways to convert a Set into an array.

Using Spread Syntax

The easiest approach is the spread operator, which unpacks all Set values into a new array:

const mySet = new Set([1, 2, 3, 4, 5]);
const myArray = [...mySet];

console.log(myArray); // [1, 2, 3, 4, 5]
console.log(Array.isArray(myArray)); // true

Using Array.from()

The Array.from() method also creates an array from any iterable, including Sets:

const mySet = new Set(['apple', 'banana', 'cherry']);
const myArray = Array.from(mySet);

console.log(myArray); // ['apple', 'banana', 'cherry']

Why Convert?

Once you have an array, you can use all the array methods you know:

const numbers = new Set([1, 2, 3, 4, 5]);
const doubled = [...numbers].map(n => n * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

Which Method to Use?

Both approaches work identically for simple conversions. Spread syntax ([...set]) is slightly shorter and more common in modern code. Array.from() becomes more powerful when you need transformations during conversion (though you haven't learned that yet).

Key Takeaway: Use [...mySet] or Array.from(mySet) to convert any Set into an array, unlocking all array methods for further data manipulation.