Javascript tutorials - 3 ways to convert Set to Arrays


This post talks about  3 ways to convert Set type to Array in JavaScript.

  1. forEach loop
  2. ES6 spread syntax
  3. Using Array from function

forEach loop

 forEach loop is one of the loop syntax to iterates the elements in collectons set.
Its syntax forEach(callback,[arg]) callback is the function which be called for each element of an collections.
It takes three input parameters - Current element(current element),index (index position, optional), and array (new array called for each element)

  
const arrayObj = [];  
mySet.forEach(element=> arrayObj.push(element));console.log(arrayObj); //[ 21, 3, 10 ]  
console.log(typeof arrayObj); //object  

ES6 spread new syntax 

ES6 introduced spread operator syntax.
Spread operator (..) allows to expand the collection and expected values atleast one element It is simple with spread operator

var mySet = new Set([21, 3, 10,21]);  
  
let arrayObj= [...mySet];  
  
  
console.log(arrayObj);//[ 21, 3, 10 ]  
console.log(typeof arrayObj); //object  

Native from function in array.

 from() function create and returns a new array from an input iterate collection like array,map,set , and each element is iterated.
Syntax is Array.from(collection of objects);

  
var mySet = new Set([21, 3, 10,21]);  
  
let arrayObj=Array.from(mySet.values());  
  
console.log(arrayObj); //[ 21, 3, 10 ]  
console.log(typeof arrayObj); //object  

Similar Posts