Explain Codes LogoExplain Codes Logo

How to convert Set to Array?

javascript
functions
callbacks
iterators
Nikita BarsukovbyNikita Barsukov·Dec 24, 2024
TLDR

There are two quick ways to convert a Set into an Array. Use either spread syntax ...:

const mySet = new Set(['a', 'b', 'c']); // Awesome set. const myArray = [...mySet]; // Just like magic!

Or use Array.from():

const myArrayFromSet = Array.from(mySet); // Easy way, huh?

Method breakdown and examples

Beyond the fast answers, let's dive deeper into the process and peek at other handy alternatives.

Using forEach to loop and transform

If you are doing something beyond a plain conversion and looking to customize, Set.forEach comes to the rescue:

const mySet = new Set([1, 2, 3]); // Just a humble set. let myArray = []; mySet.forEach(value => { myArray.push(value * 2); // Biceps mode, double the size. });

Converting by values

Set.values() spins an iterator. Convenient when working on result digestion by iterators:

const myValuesIterator = mySet.values(); // Iterator in disguise. const myArrayFromIterator = Array.from(myValuesIterator); // Back to being an Array!

Sneaky compatibility issues

ES6 features — cool, right? But remember, old browsers. They do not like too cool stuff. Use Babel or TypeScript to keep them happy.

Advanced usage, potential issues and performance tips

Time to delve into the Arcana. Here are the tricks and potential pitfalls along the journey of conversion.

The deprecated pitfall

Remember the array comprehension? Kind of old school. And also deprecated. Modern code demands modern measures. Stick to the new kids on the block.

Order, order!

Keep in mind, the array resulting from a Set conversion retains the original insertion order. And if order matters, .sort() is your friend:

const mySortedArray = Array.from(mySet).sort((a, b) => a - b); // Sorting hat, is it you? 🧙‍♂️

The lodash detour

Set has an inherent unique element guarantee. It makes the _.uniq of lodash a tad bit redundant. Remember, every detour comes at a cost.