Quiz

How do you convert a `Set` to an array in JavaScript?

Topics
JavaScript

TL;DR

To convert a Set to an array in JavaScript, you can use the Array.from() method or the spread operator. For example:

const mySet = new Set([1, 2, 3]);
const myArray = Array.from(mySet);
// OR const myArray = [...mySet];
console.log(myArray); // Output: [1, 2, 3]

Using Array.from()

The Array.from() method creates a new, shallow-copied array instance from an array-like or iterable object, such as a Set.

const mySet = new Set([1, 2, 3]);
const myArray = Array.from(mySet);
console.log(myArray); // Output: [1, 2, 3]

Using the spread operator

The spread operator (...) can be used to expand the elements of a Set into an array.

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

Performance considerations

Both Array.from(set) and [...set] iterate the Set into a new array. If conversion is a performance bottleneck, benchmark both methods with representative data.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise 1 of 2
Check your understanding Exercise 1 of 2

What does this code log?

const values = new Set([3, 1, 3, 2]);
const array = [...values];
console.log(array.join(','));