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]
*/
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);
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);
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]
*/
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 😃!