Open In App

How to convert Map keys to an array in JavaScript ?

In this article, we are given a Map and the task is to get the keys of the map into an array using JavaScript. We can access the keys by using the Map keys() method.

We have a few methods to do this that are described below:



Approach 1: Using array.from() Method

Example: This example uses an array.from() method to get the keys of the Map in the array. 






let myMap = new Map().set('GFG', 1).set('Geeks', 2);
let array = Array.from(myMap.keys());
 
//Return the length of array
console.log(array.length);

Output
2

Approach 2: Using [ …Map.keys() ] Method

Example: This example uses the [ …Map.keys() ] method to get the keys of the Map in the array. 




let myMap = new Map().set('GFG', 1).set('Geeks', 2);
let array = [...myMap.keys()];
 
//return the length of array
console.log(array.length);

Output
2

Approach 3: Using for…of Loop Method

Example: This example shows the implementation of the above-explained approach.




let myMap = new Map().set('GFG', 1)
    .set('Geeks', 2).set('Geeksforgeeks', 3);
let arr = [];
for (let key of myMap.keys()) {
    arr.push(key);
}
console.log(arr);

Output
[ 'GFG', 'Geeks', 'Geeksforgeeks' ]

Approach 4: Using Map.forEach() Method

Example: This example shows the implementation of the above-explained approach.




let myMap = new Map().set('GFG', 1)
    .set('Geeks', 2)
    .set('Geeksforgeeks', 3);
let arr = [];
myMap.forEach((values, keys) => {
    arr.push(keys);
});
console.log(arr);

Output
[ 'GFG', 'Geeks', 'Geeksforgeeks' ]

Approach 5: Using Lodash _.toArray() Method

In this approach, we are using Lodash _.toArray() method that accept any value and convert it into an array.

Example: This example shows the implementation of the above-explained approach.




// Requiring the lodash library
const _ = require("lodash");
 
let myMap = new Map().set('GFG', 1).set('Geeks', 2);
let arr = _.toArray(myMap.keys());
 
// Use of _.toArray() method
console.log(arr.length);

Output:

2

Article Tags :