. Advertisement .
..3..
. Advertisement .
..4..
If you are confused with the problem How to convert a Set to an Array in JavaScript, let’s follow our article. We will help you to handle it.
What can we do to convert a Set to an Array in JavaScript?
Option 1: Utilizing Array.from() method
Utilizing Array.from() method is the simplest solution to convert a Set to an Array in JavaScript. A new Array from an array like object or iterable objects such as Set, Map,… will be returned by this method.
Syntax:
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>
Output:
GeeksforGeeks
welcome,to,GFG
Option 2: Utilizing spread operator
Utilizing spread operator also is a great solution to convert set to array.
The syntax:
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.
The syntax:
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 ]
*/
Conclusion
We hope the above solutions will help you to solve with the problem How to convert a Set to an Array in JavaScript. If you have any questions or any problems, let’t contact with us by leaving your comment below. ITtutoria is always here to help you. Thanks for your reading!
Read more
→ How To Convert a Comma Separated String to Array in JavaScript
Leave a comment