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.

Syntax:

mapName.keys();

Example: The below code explains the practical use of the keys() method to convert the keys of a Map into a Set.

Javascript




const dummyMap = new Map();
dummyMap.set('type1', 'Company');
dummyMap.set('name1', 'w3wiki');
dummyMap.set('type2', 'Cricketer');
dummyMap.set('name2', 'Virat Kohli');
console.log("Initial Map: ", dummyMap);
 
const createdSet = new Set(dummyMap.keys());
console.log("Created Keys Set: ", createdSet);


Output

Initial Map:  Map(4) {
  'type1' => 'Company',
  'name1' => 'w3wiki',
  'type2' => 'Cricketer',
  'name2' => 'Virat Kohli'
}
Created Keys Set:  Set(4) { 'type1', 'name1', 'type2', 'name2' }


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....