How to convert Set to Array?

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);

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.


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:

Note: safer for TypeScript.

const array = Array.from(mySet);
  • Simply spreading the Set out in an array:

Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856). It's safer to use Array.from above instead.

const array = [...mySet];
  • The old-fashioned way, iterating and pushing to a new array (Sets do have forEach):
const array = [];
mySet.forEach(v => array.push(v));
  • Previously, using the non-standard, and now deprecated array comprehension syntax:
const array = [v for (v of mySet)];