Convert a Set to an Array in JavaScript
In this guide, we will explore different methods to convert a set to an array in JavaScript.
Using an Array.from() method
The Array.from()
method creates a new array from an array-like or iterable object such as a string, map, or set.
Let’s see an example:
var mySet = new Set([1, 2, 3, 4]);
var myArray = Array.from(mySet);
console.log(myArray); // Output: [1, 2, 3, 4]
Using a spread operator
The spread operator …
allows us to spread the elements of an array-like or iterable object as individual elements.
Let’s see an example:
var mySet = new Set([1, 2, 3, 4]);
console.log([...mySet]); // Output: [1, 2, 3, 4]
Using a for…of loop
In this method, we iterate over each element of the set using a for…of
loop and add each element to the array individually.
Here’s an example:
var mySet = new Set([1, 2, 3, 4]);
var myArray = [];
for (var item of mySet) {
myArray.push(item);
}
console.log(myArray); // Output: [1, 2, 3, 4]
In the above example, we create an empty array myArray
and then use a for…of
loop to iterate over each element of the mySet
set. Within the loop, we push each element into the myArray
using the push()
method.
The resulting output will be an array [1, 2, 3, 4]
containing all the elements of the set converted into an array.
Using a forEach() method
In this method, we use the forEach()
method to iterate over each element of the set and add each element to the array individually.
Here’s an example:
var mySet = new Set([1, 2, 3, 4]);
var myArray = [];
mySet.forEach(item => myArray.push(item));
console.log(myArray); // Output: [1, 2, 3, 4]
In the above example, we create an empty array myArray
. Then, we call the forEach()
method on the mySet
set and pass the callback function as the argument. The callback function takes each item and pushes it into the myArray
.
The resulting output will be an array [1, 2, 3, 4]
containing all the elements of the set converted into an array.