How to Convert a Set to Array in JavaScript

Published Oct 26, 2020  ∙  Updated May 2, 2022

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

const dogSet = 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 = [];
dogSet.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(dogSet);

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 = [...dogSet];