How to Convert Set to Array in JavaScript

In JavaScript, a Set is a collection of unique values, while an Array is an ordered list of values.

Sometimes, it is necessary to convert a Set to an Array for processing data in a specific format.

In this Javascript tutorial, we will discuss various methods of converting a Set to an Array in JavaScript.


Using the Spread Operator

The Spread operator is a modern method of converting a Set to an Array.

The spread operator (…) allows you to expand an iterable object, such as a Set, into multiple elements.

This is a simple and efficient way of converting a Set to an Array.

let set = new Set([1, 2, 3, 4, 5]);
let array = [...set];
console.log(array); // [1, 2, 3, 4, 5]

Using Array.from()

Array.from() is a static method that creates a new, shallow-copied Array instance from an array-like or iterable object.

It is another efficient method of converting a Set to an Array.

let set = new Set([1, 2, 3, 4, 5]);
let array = Array.from(set);
console.log(array); // [1, 2, 3, 4, 5]

Using forEach()

The forEach() method is used to execute a function for each element in an Array.

It can also be used to convert a Set to an Array by pushing each element of the Set into a new Array.

let set = new Set([1, 2, 3, 4, 5]);
let array = [];
set.forEach(function(value) {
  array.push(value);
});
console.log(array); // [1, 2, 3, 4, 5]

Using for…of Loop

The for…of loop is used to iterate over the elements of an Array.

It can also be used to convert a Set to an Array by pushing each element of the Set into a new Array.

let set = new Set([1, 2, 3, 4, 5]);
let array = [];
for (let value of set) {
  array.push(value);
}
console.log(array); // [1, 2, 3, 4, 5]

Conclusion

In this tutorial, we discussed various methods of converting a Set to an Array in JavaScript.

The methods discussed include using the Spread operator, Array.from(), forEach() method, and for…of loop.

Each method has its own advantages and disadvantages, and the choice of method depends on the specific use case.

It is recommended to choose the most appropriate method for the task at hand.