Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Set to Array?

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 ?

like image 769
c69 Avatar asked Nov 19 '13 11:11

c69


People also ask

Can we convert Set to array in Java?

Set to arrayThe Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. Use this method to convert a Set object to an array.


2 Answers

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)]; 
like image 163
adeneo Avatar answered Sep 23 '22 22:09

adeneo


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); 
like image 33
c69 Avatar answered Sep 21 '22 22:09

c69