Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Javascript `Set` to an array [duplicate]

There doesn't seem to be an easy and elegant way of converting a Javascript Set to an array.

var set = new Set();
set.add("Hello");
set.add("There");
set.add(complexObject);

var setConvertedToArray = convertSetToArray(set);

console.log( setConvertedToArray ); // ["Hello", "There", ►Object ]

A map feels about right, but the Set prototype only has a forEach.

Yuck:

function convertSetToArray(set) {
  var a = [];
  set.forEach( x => a.push(x) ); 
  return a;
}

Anyone know of a nice way to convert a Set to an array?

like image 900
aaaidan Avatar asked Jan 11 '16 03:01

aaaidan


People also ask

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

Can array have duplicate values JavaScript?

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.


1 Answers

Some ways to do it:

[...set];
[...set.keys()];
[...set.values()];
Array.from(set);
Array.from(set.keys());
Array.from(set.values());
like image 103
Oriol Avatar answered Sep 21 '22 19:09

Oriol