How to use the Array.from() method In Javascript
The Array.from() method can also be used to convert a Map into a Set by passing the Map as parameter to it.
Syntax:
Array.from(mapName);
Example: The below code implements the Array.from() method to convert a Map into a Set.
Javascript
const dummyMap = new Map(); dummyMap.set( 'name1' , 'w3wiki' ); dummyMap.set( 'name2' , 'Virat Kohli' ); console.log( "Initial Map: " , dummyMap); const createdSet = new Set(Array.from(dummyMap)); console.log( "Created Set: " , createdSet); |
Initial Map: Map(2) { 'name1' => 'w3wiki', 'name2' => 'Virat Kohli' } Created Set: Set(2) { [ 'name1', 'w3wiki' ], [ 'name2', 'Virat Kohli' ] }
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, there you can use the below methods for the conversion.
Table of Content
- Converting Map keys into Set
- Converting Map values into Set
- Converting Keys and Values of a Map into Set
- Using the spread operator syntax
- Using the Array.from() method