Option 1: Utilizing Array.from() method
arr = Array.from(element)
Element: An element can be a string, an object, or a set.
Arr: The variable we’ll use to hold the result of our Array.from function is called arr.
Look at the following example to understand more about this method:
<!DOCTYPE html> <html> <head> <title> Convert Set to Array </title> </head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script> const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); document.write(Array.from(set)); </script> </center> </body> </html>
Option 2: Utilizing spread operator
Utilizing spread operator also is a great solution to convert set to array.
var variablename = [...value];
The spread operator in the syntax above will target all values in a specific variable. The spread operator is helpful when we want to copy, expand or combine math objects with other objects. Look at the example below:
var s = new Set([2, 4, 6, 8]); let arr = [...s]; console.log(arr); /* Output: [ 2, 4, 6, 8 ] */
Option 3: Utilizing Set.prototype.forEach() function
A different approach is to add each Set component to the array separately.
obj.forEach((x) => //Statements for every element//);
In each iteration of the forEach() function, x: is the value assigned to each element.
obj: Object with items being iterated; it can be an object, a string, a set, a map, or a function.
The forEach() method makes this simple to accomplish, as shown below:
var s = new Set([2, 4, 6, 8]); let arr = ; s.forEach(x => arr.push(x)); console.log(arr); /* Output: [ 2, 4, 6, 8 ] */