How to convert Set to 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 items that are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order.
A set can be converted to an array in JavaScript by the following ways:
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, a set will be converted into an array using the Array.from() method
HTML
< script > const set = new Set(['welcome', 'to', 'GFG']); Array.from(set); console.log(Array.from(set)); </ script > |
Output:
welcome,to,gfg
JavaScript spread Operator: Using of spread operator can also help us convert the Set to an array.
Syntax:
var variablename = [...value];
Example: In this example, a set will be converted into an array using the spread operator.
HTML
< script > const set = new Set(['GFG', 'JS']); const array = [...set]; console.log(array); </ script > |
Output:
GFG,JS
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.
HTML
< script > var gfgSet = new Set(); var gfgArray = []; gfgSet.add("Geeks"); gfgSet.add("for"); // duplicate item gfgSet.add("Geeks"); var someFunction = function( val1, val2, setItself) { gfgArray.push(val1); }; gfgSet.forEach(someFunction); console.log("Array: " + gfgArray); </ script > |
Output:
Array: Geeks,for
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Please Login to comment...