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);


Output

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

Similar Reads

Converting Map keys into Set

You can create a Set that contains the keys of the Map as values using the keys() method on the Map to get its keys and store them as values of the Set....

Converting Map values into Set

...

Converting Keys and Values of a Map into Set

The values() method can be used with the Map to get its values and store them into a Set as its values. This method will convert the Map values into a Set....

Using the spread operator syntax

...

Using the Array.from() method

A Set that contains both the keys and values of the Map as values can also be created using the entries() method to get the Map keys and values and store them into a Set....