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

1. Using Set constructor

The recommended solution is to pass the array to the set constructor, which accepts an iterable object. This is demonstrated below:

Download  Run Code

2. Using Array.prototype.map() function

The map() method can also be used to transform a regular array into a set:

Download  Run Code

 
To convert an array of objects to a set, you can use the map() method in the following manner:

Download  Run Code

3. Using Array.prototype.forEach() function

Another solution is to individually add each array element to the set object. This can be easily done using the forEach() method, as shown below:

Download  Run Code

4. Using Array.prototype.reduce() function

Finally, you can use the reduce() method in the following manner to transform an array into a set.

Download  Run Code

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