Ad

Convert A Javascript `Set` To An Array

- 1 answer

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?

Ad

Answer

Some ways to do it:

[...set];
[...set.keys()];
[...set.values()];
Array.from(set);
Array.from(set.keys());
Array.from(set.values());
Ad
source: stackoverflow.com
Ad