How to convert a Set to an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by David Marcu

Convert a Set to an Array #

To convert a Set to an array, pass the Set as a parameter to the Array.from() method, e.g. Array.from(mySet). The Array.from method creates a new array from an iterable object, such as a Set.

index.js
const set = new Set(['a', 'b', 'c']); const arr = Array.from(set); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] console.log(arr.length); // ๐Ÿ‘‰๏ธ 3

The only parameter we passed to the Array.from method is an iterable object.

The method converts the iterable into an array and returns a new array instance.

This is the recommended approach when using TypeScript, because the compiler often complains when using the spread operator (...) with iterators.

An alternative approach is to use the spread operator (...).

Convert a Set to an Array in using spread operator #

To convert a Set to an array, use the spread operator (...) - [...mySet]. The spread operator allows us to unpack the values of an iterable, such as a Set, into an array..

index.js
const set = new Set(['a', 'b', 'c']); const arr = [...set]; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] console.log(arr.length); // ๐Ÿ‘‰๏ธ 3

We used the spread operator to include all of the elements the Set has into a new array.

This is the most commonly used approach to convert a Set into an array.

You could also do this with multiple Sets.

index.js
const set1 = new Set(['a', 'b']); const set2 = new Set(['x', 'y']); const arr = [...set1, ...set2]; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'x', 'y'] console.log(arr.length); // ๐Ÿ‘‰๏ธ 4

Convert a Set to an Array in using forEach #

To convert a Set to an array:

  1. Declare a variable and set it to an empty array.
  2. Use the forEach() method to iterate over the Set.
  3. On each iteration, push the value into the array.
index.js
const arr = []; set.forEach(value => { arr.push(value); }); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] console.log(arr.length); // ๐Ÿ‘‰๏ธ 3

The function we passed to the Set.forEach method gets called with each value in the Set.

On each iteration we simply push the value into the array.

This is definitely the most verbose and manual of the 3 approaches. I prefer either of the other 2 ways to convert a Set into an array.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee