How to convert Set to Array?
Solution 1:
if no such option exists, then maybe there is a nice idiomatic 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
let array = Array.from(mySet);
Simply spreading
the Set out in an array
let array = [...mySet];
The old-fashioned way, iterating and pushing to a new array (Sets do have forEach
)
let array = [];
mySet.forEach(v => array.push(v));
Previously, using the non-standard, and now deprecated array comprehension syntax:
let array = [v for (v of mySet)];
Solution 2:
via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll
It turns out, we can use spread
operator:
var myArr = [...mySet];
Or, alternatively, use Array.from
:
var myArr = Array.from(mySet);
Solution 3:
Assuming you are just using Set
temporarily to get unique values in an array and then converting back to an Array, try using this:
_.uniq([])
This relies on using underscore or lo-dash.
Solution 4:
Perhaps to late to the party, but you could just do the following:
const set = new Set(['a', 'b']);
const values = set.values();
const array = Array.from(values);
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:
const set = new Set(['a', 'b']);
const array = [...set]; // or Array.from(set)