DEV Community

Cover image for How to convert a Set to an Array in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert a Set to an Array in JavaScript?

Originally posted here!

To convert a Set to an array, you can use the from() method from the global Array object in JavaScript.

TL;DR

// initialize a set
const uniqueNumbers = new Set();

// add values to the `uniqueNumbers` set
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(3);

// convert `uniqueNumbers` set to an array
// using the Array.from() method
const uniqueNumbersArr = Array.from(uniqueNumbers);

// log the output of `uniqueNumbersArr` array
console.log(uniqueNumbersArr);

/*

OUTPUT:
-------

[1, 2, 3]

*/
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a set called uniqueNumbers and add some values of 1, 2, and 3 to the set using the add() method like this,

// initialize a set
const uniqueNumbers = new Set();

// add values to the uniqueNumbers set
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(3);
Enter fullscreen mode Exit fullscreen mode

Now we have a valid set of unique numbers.

To convert the above uniqueNumbers set to an array, we can use the Array.from() method and:

  • pass the uniqueNumbers set as an argument to the method.
  • The method returns a new array with all the values of the uniqueNumbers set as the array elements.

It can be done like this,

// initialize a set
const uniqueNumbers = new Set();

// add values to the `uniqueNumbers` set
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(3);

// convert `uniqueNumbers` set to an array
// using the Array.from() method
const uniqueNumbersArr = Array.from(uniqueNumbers);
Enter fullscreen mode Exit fullscreen mode

Now we have converted the uniqueNumbers set to an array. Yay 🎉!

Let's also log the output of the uniqueNumbersArr to the console.

It can be done like this,

// initialize a set
const uniqueNumbers = new Set();

// add values to the `uniqueNumbers` set
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(3);

// convert `uniqueNumbers` set to an array
// using the Array.from() method
const uniqueNumbersArr = Array.from(uniqueNumbers);

// log the output of `uniqueNumbersArr` array
console.log(uniqueNumbersArr);

/*

OUTPUT:
-------

[1, 2, 3]

*/
Enter fullscreen mode Exit fullscreen mode

As you see from the above output that the uniqueNumbers set is successfully converted into an array in JavaScript.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)