Quiz

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

Topics
JavaScript
在GitHub上编辑

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];

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

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 methods are efficient and commonly used. However, the spread operator is often considered more concise and readable. Performance differences are generally negligible for most use cases, but for very large sets, you might want to benchmark both methods to see which performs better in your specific scenario.

Further reading

在GitHub上编辑