0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Set to Array Easily

You can convert a Set to an Array in JavaScript by using the spread operator like const arr = [...mySet] or by using Array.from(mySet).
📋

Examples

Inputnew Set([1, 2, 3])
Output[1, 2, 3]
Inputnew Set(['a', 'b', 'c'])
Output['a', 'b', 'c']
Inputnew Set([])
Output[]
🧠

How to Think About It

To convert a Set to an Array, think of taking all unique items from the Set and putting them into a list format. Since Sets store unique values, you just need a way to collect those values into an array structure, which can be done easily with built-in JavaScript features.
📐

Algorithm

1
Get the Set you want to convert.
2
Use the spread operator or Array.from() to collect all elements from the Set.
3
Store the collected elements in a new Array variable.
4
Return or use the new Array as needed.
💻

Code

javascript
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray);
Output
[1, 2, 3]
🔍

Dry Run

Let's trace converting Set {1, 2, 3} to an Array using the spread operator.

1

Start with Set

mySet = Set {1, 2, 3}

2

Use spread operator

myArray = [...mySet]

3

Resulting Array

myArray = [1, 2, 3]

StepOperationResult
1Define SetSet {1, 2, 3}
2Spread Set into Array[1, 2, 3]
💡

Why This Works

Step 1: Spread operator collects values

The ... operator takes each value from the Set and places it into a new Array.

Step 2: Array.from alternative

Array.from() creates a new Array from any iterable like a Set.

🔄

Alternative Approaches

Array.from()
javascript
const mySet = new Set([4, 5, 6]);
const myArray = Array.from(mySet);
console.log(myArray);
This method is clear and works well for any iterable, but slightly longer than spread syntax.
Using for...of loop
javascript
const mySet = new Set([7, 8, 9]);
const myArray = [];
for (const item of mySet) {
  myArray.push(item);
}
console.log(myArray);
This manual method works but is more verbose and less elegant than built-in methods.

Complexity: O(n) time, O(n) space

Time Complexity

Converting a Set to an Array requires visiting each element once, so it takes linear time proportional to the number of elements.

Space Complexity

A new Array is created to hold all elements, so space used grows linearly with the Set size.

Which Approach is Fastest?

The spread operator and Array.from() have similar performance and readability. Manual loops are slower and more verbose.

ApproachTimeSpaceBest For
Spread operator [...mySet]O(n)O(n)Quick and readable conversion
Array.from(mySet)O(n)O(n)Clear method for any iterable
Manual for...of loopO(n)O(n)When custom processing needed
💡
Use the spread operator [...mySet] for a quick and readable conversion.
⚠️
Trying to convert a Set to Array by calling mySet.toArray(), which does not exist.