Start your developer blog today!
Email me

How to Convert a Set to Array in JavaScript

Oct 26, 2020 1 min read

We have a set that we want to convert into an array. There are a couple of ways to go about this.

const set =  new Set(['corgi', 'shih tzu', 'pug']);
// Set(3) {"corgi", "shih tzu", "pug"}

Using a for Loop

Traditionally, we can iterate through every element in the set and add it to an array, but order is not guaranteed.

let arr = [];
set.forEach(elem => arr.push(elem));

Using Array.from()

We could also use Array.from() to create an array from an iterable object.

const arr = Array.from(set);

Using the Spread Operator

The most elegant (in my opinion) is to use the spread operator dump all the elements from the set into an array.

const arr = [...set];

More JavaScript Articles