There
are three ways to convert a set to an array
HelloWorld.js
HelloWorld.js
a. Using Array.from
method
b. Using Spread operator
c. Manually inserting
the elements from set to array
Using Array.from method
HelloWorld.js
var countries = new Set(); countries.add("India"); countries.add("Australia"); countries.add("Canada"); countries.add("Germany"); var arr = Array.from(countries); console.log(arr);
Output
Array(4)
[ "India", "Australia", "Canada",
"Germany" ]
Using Spread operator
Example
var
arr = [...countries];
var countries = new Set(); countries.add("India"); countries.add("Australia"); countries.add("Canada"); countries.add("Germany"); var arr = [...countries]; console.log(arr);
Output
Array(4)
[ "India", "Australia", "Canada",
"Germany" ]
Manually inserting
the elements from set to array
var
arr = new Array()
for(var
ele of countries){
arr.push(ele);
}
var countries = new Set(); countries.add("India"); countries.add("Australia"); countries.add("Canada"); countries.add("Germany"); var arr = new Array() for(var ele of countries){ arr.push(ele); } console.log(arr);
Output
Array(4) [ "India", "Australia", "Canada", "Germany" ]
Array(4) [ "India", "Australia", "Canada", "Germany" ]
No comments:
Post a Comment