JavaScript program to convert a set to array:
Set holds unique values. We can’t have more than one same value in a JavaScript set. But in an array, we can have an item more than one time. Sometimes, we might need to convert a set to an array. In this post, I will show you how to convert a set to an array in JavaScript.
Using Array.from():
Array.from is a static method that creates a new instance of an array with the passed iterable object. If we pass a set, it convers that set to an array.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
let convertedArray = Array.from(set);
console.log(convertedArray);
It will print:
[ 1, 2, 3, 4 ]
Using Spread syntax:
Using spread syntax, we can convert a set to an array:
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
let convertedArray = [...set];
console.log(convertedArray);
It prints the same output.
Using forEach:
We can always iterate throught the set items and insert them to an empty array. This is a not a recommended method to use.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
let convertedArray = [];
set.forEach(v => convertedArray.push(v));
console.log(convertedArray);
The output is same.
You might also like:
- 2 different JavaScript program to remove last n characters from a string
- JavaScript program to add two numbers - 3 different ways
- 2 different JavaScript program to calculate age from date of birth
- How to print a multiplication table in HTML,CSS, and JavaScript
- JavaScript program to get the selected value from a dropdown list of items
- How to stop forEach() method in JavaScript