Convert a Set to an array in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 |
// create a set of integers var s = new Set([2, 4, 6, 8]); // convert the set to an array of same type let intArr = Array.from(s); console.log(intArr); // Output: [ 2, 4, 6, 8 ] // convert the set to an array of strings let strArr = Array.from(s, x => String(x)); console.log(strArr); // Output: [ '2', '4', '6', '8' ] |
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:
|
1 2 3 4 5 6 |
var s = new Set([2, 4, 6, 8]); // spread the set into an array let arr = [...s]; console.log(arr); // Output: [ 2, 4, 6, 8 ] |
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:
|
1 2 3 4 5 6 7 8 9 |
var s = new Set([2, 4, 6, 8]); // create an empty array let arr = []; // iterate over the set and push each element to the array s.forEach(x => arr.push(x)); console.log(arr); // [ 2, 4, 6, 8 ] |
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.
|
1 2 3 4 5 6 |
var _ = require('lodash'); // or underscore var arr = [2, 4, 6, 8, 4, 5]; var distinct = _.uniq(arr); console.log(distinct); // [ 2, 4, 6, 8, 5 ] |
That’s all about converting a Set to an array 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 :)