![]() |
A Set is a collection of unique values. It stores only the data in the form of values while a Map can store the data in the form of key-value pairs. These are the different ways of converting a Set to a Map in JavaScript: Table of Content Using the Array.from() methodThe Array.from() method can be used to convert a Set to a Map by passing the Map and a callback function to set the keys and the values of the Map as parameters to this method. Syntax:Array.from(setName, ()=>{});
Example: The below code example uses the Array.from() method to convert a Set to a Map. Javascript
Output
Initial Set: Set(2) { 'GeeksforGeeks', 'Virat Kohli' } Created Map: Map(2) { 13 => 'GeeksforGeeks', 11 => 'Virat Kohli' } Using the Spread Operator with map() methodThe spread operator is used to spread the data of the Set and the the map() method will be used to iterate over them to store them in an empty Map. Syntax:[...setName].map(()=>{});
Example: The below code is the practical implementation of the above approach to convert a Set into a Map. Javascript
Output
Initial Set: Set(2) { 'GeeksforGeeks', 'Virat Kohli' } Created Map: Map(2) { 13 => 'GeeksforGeeks', 11 => 'Virat Kohli' } Using the reduce() methodThe JavaScript reduce() method can be used to convert the Set to a Map when it is used with the spread operator. Syntax:[...setName].reduce(()=>{}); Example: The below code shows the practical implementation of the reduce() method to convert a Set to a Map. Javascript
Output
Initial Set: Set(2) { 'GeeksforGeeks', 'Virat Kohli' } Created Map: Map(2) { 13 => 'GeeksforGeeks', 11 => 'Virat Kohli' } Using the forEach() methodThe forEach() method can be used to iterate through each element of the Set to set them as key-value pair of the Map one by one. Syntax:setName.forEach(()=>{});
Example: The below code can be used to convert a Set to a Map using the forEach() method. Javascript
Output
Initial Set: Set(2) { 'GeeksforGeeks', 'Virat Kohli' } Created Map: Map(2) { 13 => 'GeeksforGeeks', 11 => 'Virat Kohli' } Using the for of loopThe for of loop can be used to get the items of the Set one by one and then set them as the key value pairs of the Map using the Map set() Method. Syntax:for(const itemName of setName){}
Example: The below code implements the for of loop to convet a Set to a Map in JavaScript. Javascript
Output
Initial Set: Set(2) { 'GeeksforGeeks', 'Virat Kohli' } Created Map: Map(2) { 13 => 'GeeksforGeeks', 11 => 'Virat Kohli' } |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |