This post will discuss how to convert a Set to an array in JavaScript.

There are several methods to convert a set to an array in JavaScript. Here are some of the functions we can use:

1. Using Array.from() function

The Array.from() function is useful for creating shallow-copied Array instances from iterable objects, such as sets. This function accepts a set as input and returns an array of the same elements. It was added to the Array object with ES6. It can also accept a mapping function as the second argument to convert the values to another type or perform some operation on them. For example:

Download  Run Code

2. Using Spread operator

You can also use the Spread operator for converting the set to an array. The spread syntax allows the set to be expanded where an array literal is expected. This function was introduced in the ES6 specification of JavaScript. Its usage is demonstrated below:

Download  Run Code

3. Using Set.prototype.forEach() function

Another solution is to individually add each element in the set to the array. This can be easily done using the forEach() function. This function iterates over the elements of an iterable object, such as a set, and pushes them to a new array. Here’s an example of this approach:

Download  Run Code

4. Using Lodash/Underscore Library

In case you’re using Set as an intermediate data structure for removing duplicate values from the array, the code can be simplified using underscore or lodash JavaScript libraries. The following example creates a duplicate-free version of an array by using the uniq() function.

Download Code

That’s all about converting a Set to an array in JavaScript.