This article will show you how to convert a Set to an Array in JavaScript. To convert a Set into an Array, we need to know the main characteristics of a set. A set is a collection of unique items, i.e. no element can be repeated. Set in ES6 are ordered i.e. elements of the set can be iterated in the insertion order.
Methods to convert set to array:
A set can be converted to an array in JavaScript in the following ways:
Method 1: Using JavaScript Array.from() Method
This method returns a new Array from an array like an object or iterable objects like Map, Set, etc.
Syntax:
Array.from(arrayLike_object);
Example: In this example, we will convert a Set into an Array using the Array.from() method
Javascript
// Creating new set let set = new Set([ 'welcome' , 'to' , 'GFG' ]); // converting to set let arr = Array.from(set); // Display console.log(arr); |
[ 'welcome', 'to', 'GFG' ]
Method 2: Using JavaScript Spread Operator
Using of spread operator can also help us to convert the Set to an Array.
Syntax:
let variablename = [...value];
Example: In this example, a set will be converted into an array using the spread operator.
Javascript
// Input set let set = new Set([ 'GFG' , 'JS' ]); // Convert using spread operator let array = [...set]; //Display output console.log(array); |
[ 'GFG', 'JS' ]
Method 3: Using JavaScript forEach() Method
The arr.forEach() method calls the provided function once for each element of the array.
Example: In this example, a set will be converted into an array using the forEach() method.
Javascript
// Create input set let newSet = new Set(); let arr = []; newSet.add( "Geeks" ); newSet.add( "for" ); // duplicate item newSet.add( "Geeks" ); let someFunction = function ( val1, val2, setItself) { arr.push(val1); }; newSet.forEach(someFunction); // Display output console.log( "Array: " + arr); |
Array: Geeks,for
JavaScript is best known for web page development but is also used in various non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.