How to convert Set to Array?
There are two quick ways to convert a Set into an Array. Use either spread syntax ...
:
Or use Array.from()
:
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:
Converting by values
Set.values()
spins an iterator. Convenient when working on result digestion by iterators:
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:
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.
Was this article helpful?