Convert an array to set in JavaScript
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:
|
1 2 3 4 5 6 7 8 |
var arr = [ 1, 3, 2, 3, 5 ]; var set = new Set(arr); console.log(set); /* Output: Set { 1, 3, 2, 5 } */ |
2. Using Array.prototype.map() function
The map() method can also be used to transform a regular array into a set:
|
1 2 3 4 5 6 7 8 9 10 |
var arr = [ 1, 3, 2, 3, 5 ]; var set = new Set(); arr.map(item => set.add(item)); console.log(set); /* Output: Set { 1, 3, 2, 5 } */ |
To convert an array of objects to a set, you can use the map() method in the following manner:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var people = [ { name: 'Josh', age: 15 }, { name: 'Mark', age: 25 }, { name: 'Tim', age: 20 }, { name: 'Bob', age: 30 } ]; var set = new Set(people.map(item => item.name)); console.log(set); /* Output: Set { 'Josh', 'Mark', 'Tim', 'Bob' } */ |
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:
|
1 2 3 4 5 6 7 8 9 10 |
var arr = [ 1, 3, 2, 3, 5 ]; var set = new Set(); arr.forEach(item => set.add(item)); console.log(set); /* Output: Set { 1, 3, 2, 5 } */ |
4. Using Array.prototype.reduce() function
Finally, you can use the reduce() method in the following manner to transform an array into a set.
|
1 2 3 4 5 6 7 8 9 10 |
var arr = [ 1, 3, 2, 3, 5 ]; var set = new Set(); arr.reduce((_, e) => set.add(e), null); console.log(set); /* Output: Set { 1, 3, 2, 5 } */ |
That’s all about converting an array to a set in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)