snippetjavascriptCritical
How to convert Set to Array?
Viewed 0 times
arrayconverthowset
Problem
Set seems like a nice way to create Arrays with guaranteed unique elements, but it does not expose any good way to get properties, except for generator [Set].values, which is called in an awkward way of
This would have been ok, if you could call
I've tried
So, the question: Is there any convenient inbuilt method for creating an Array with values of a given Set ? (Order of element does not really matter).
if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using
mySet.values.next().This would have been ok, if you could call
map and similar functions on Sets. But you cannot do that, as well.I've tried
Array.from, but seems to be converting only array-like (NodeList and TypedArrays ?) objects to Array. Another try: Object.keys does not work for Sets, and Set.prototype does not have similar static method.So, the question: Is there any convenient inbuilt method for creating an Array with values of a given Set ? (Order of element does not really matter).
if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using
for...of, or similar ?Solution
if no such option exists, then maybe there is a nice idiomatic
one-liner for doing that ? like, using
Indeed, there are several ways to convert a Set to an Array:
Note: safer for TypeScript.
Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856). It's safer to use
one-liner for doing that ? like, using
for...of, or similar ?Indeed, there are several ways to convert a Set to an Array:
- Using
Array.from:
Note: safer for TypeScript.
const array = Array.from(mySet);- Simply
spreadingthe Set out in an array:
Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856). It's safer to use
Array.from above instead.const array = [...mySet];- The old-fashioned way, iterating and pushing to a new array (Sets do have
forEach):
const array = [];
mySet.forEach(v => array.push(v));Code Snippets
const array = Array.from(mySet);const array = [...mySet];const array = [];
mySet.forEach(v => array.push(v));Context
Stack Overflow Q#20069828, score: 1643
Revisions (0)
No revisions yet.