Saturday, 22 December 2018

JavaScript: Convert Set to Array

There are three ways to convert a set to an array
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];

HelloWorld.js
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);
}

HelloWorld.js
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" ]



Previous                                                 Next                                                 Home

No comments:

Post a Comment