In this article we will learn how to convert a set to an array.
It is very common to convert a set to an array in JavaScript.
Problem
We have a problem, which is that we want to convert a set to an array
Imagine we have a set like this:
// Set
const set = new Set([1, 2, 3]);
console.log(set);
// Set(3) { 1, 2, 3 }
And we want to convert this set to an array.
How to solve this problem
We can solve this problem by more than one way:
- Using
Array.from()
method - Using spread operator
...
Convert a set to an array using Array.from
We can use Array.from
method to convert a set to an array.
Example
// set
const set = new Set([1, 2, 3]);
// Convert set to an array
const toArray = Array.from(set);
// Result:
console.log(toArray);
Output
[ 1, 2, 3 ]
Convert a set to an array using spread operator
We can use spread operator ...
to convert the set to an array as well.
// set
const set = new Set([1, 2, 3]);
// Convert set to an array
const toArray = [...set];
// Result:
console.log(toArray);
Output
[ 1, 2, 3 ]
Thank you for reading
Thank you for reading my blog. 🚀