Sometimes we use a set to create a data structure that doesn’t have duplicate elements.
But we’ve to convert them to an array so we can work with them more easily.
In this article, we’ll look at ways to convert a JavaScript set to a JavaScript array.
Array.from
The Array.from
static method lets us convert any iterable object into an array.
JavaScript sets are iterable objects, so we can use them to do the conversion.
For instance, we can write:
const array = Array.from(new Set([1, 2, 3]));
console.log(array)
to convert a set to an array.
We pass in the set straight into the Array.from
method to do the conversion.
Therefore, array
is:
[1, 2, 3]
Spread Operator
Another way to convert a set to an array is to use the spread operator.
The spread operator lets us spread any iterable object into an array.
Therefore, we can write:
const array = [...new Set([1, 2, 3])];
console.log(array)
Therefore, we get the same result as before.
Set.prototype.forEach
A JavaScript set has a forEach
method that lets us iterable through all the entries in the set.
It takes a callback that has the item we’re iterating through as the parameter and we can do anything with it in the body.
For instance, we can write:
const set = new Set([1, 2, 3])
const array = [];
set.forEach(v => array.push(v));
console.log(array)
to get the same result as before.
We call array.push
to append the set item v
to the array
.
Set.prototype.values and Spread Operator
A JavaScript set also has the values
method that returns an iterator with all the values of the set.
So we can spread the iterator into an array with the spread operator.
For example, we can write:
const set = new Set([1, 2, 3])
const array = [...set.values()]
console.log(array)
to spread the values in the iterator returned by set.values
into array
.
And so we get the same result as before.
for-of Loop
Since a JavaScript set is iterable, we can loop through the entries with the for-of loop.
And in the loop body, we can call push
to append the set item into the array.
To do that, we write:
const set = new Set([1, 2, 3])
const array = [];
for (const v of set) {
array.push(v)
}
console.log(array)
And we get the same result as before.
Conclusion
There’re many ways we can use to convert a set into an array.
Since JavaScript sets are iterable objects, we can use things like the spread operator, for-of loop, Array.from
, etc. to do the conversion.