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 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 ?
Using Set and converting it to an array is very similar to copying an Array...
So you can use the same methods for copying an array which is very easy in ES6
For example, you can use
...
Imagine you have this Set below:
You can simply convert it using:
and the result is:
An array and now you can use all methods that you can use for an array...
Other common ways of doing it:
or using loops like:
Assuming you are just using
Set
temporarily to get unique values in an array and then converting back to an Array, try using this:This relies on using underscore or lo-dash.
Perhaps to late to the party, but you could just do the following:
This should work without problems in browsers that have support for ES6 or if you have a shim that correctly polyfills the above functionality.
Edit: Today you can just use what @c69 suggests:
via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll
It turns out, we can use
spread
operator:Or, alternatively, use
Array.from
:Indeed, there are several ways to convert a Set to an Array:
using
Array.from
Simply
spreading
the Set out in an arrayThe old fashion way, iterating and pushing to a new array (Sets do have
forEach
)Using a fancier
for...of
loop (this doesn't seem to work in Chrome anymore)In my case the solution was:
value1 equals value2 => The value contained in the the current position in the Set. The same value is passed for both arguments
Worked under IE11.