How to convert a Set to an Array in JavaScript?

How To Convert A Set To An Array In Javascript?

If you’re confused with the issue How to convert a Set to an Array in JavaScript, let’s comply with our article. We will assist you to to deal with it.

What can we do to convert a Set to an Array in JavaScript?

Option 1: Utilizing Array.from() methodology

Utilizing Array.from() methodology is the best resolution to convert a Set to an Array in JavaScript. A brand new Array from an array like object or iterable objects similar to Set, Map,… will probably be returned by this methodology.

Syntax:

arr = Array.from(aspect)

Element: An aspect may be a string, an object, or a set.

Arr: The variable we’ll use to maintain the results of our Array.from perform is known as arr.

Look on the following instance to perceive extra about this methodology:

<!DOCTYPE html>
<html>
<head>
    <title>
        Convert Set to Array
    </title>
</head>
<physique>
    <heart>
        <h1 fashion="color:green">
          GeeksforGeeks
      </h1>
        <script>
            const set = 
               new Set(['welcome', 'to', 'GFG']);
            Array.from(set);
            doc.write(Array.from(set));
        </script>
    </heart>
</physique>
</html>

Output:

GeeksforGeeks
welcome,to,GFG

Option 2: Utilizing unfold operator

Utilizing unfold operator is also a nice resolution to convert set to array.

The syntax:

var variablename = [...value];

The unfold operator in the syntax above will goal all values in a particular variable. The unfold operator is useful once we need to copy, develop or mix math objects with different objects. Look on the instance under:

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() perform

A distinct strategy is to add every Set element to the array individually.

READ :  “Error: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms”,

The syntax:

obj.forEach((x) => //Statements for each aspect//);

In every iteration of the forEach() perform, x: is the worth assigned to every aspect.

obj: Object with objects being iterated; it may be an object, a string, a set, a map, or a perform.

The forEach() methodology makes this easy to accomplish, as proven under:

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 options will assist you to to resolve with the issue How to convert a Set to an Array in JavaScript. If you will have any questions or any issues, let’t contact with us by leaving your remark under. UnliHow is all the time right here to assist you to. Thanks on your studying!

Read extra

How To Convert a Comma Separated String to Array in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *