How to Convert a Map to Array in JavaScript

Here are three ways to convert a Map to an Array in JavaScript.

  1. Using the “Array.from()” and “Map.keys()”
  2. Using the “Spread operator” and “Map.keys()”
  3. Using “for..of loop”

Method 1: Using the Array.from() and Map.keys()

The Array.prototype.from() method creates a new array instance from an iterable object, such as a Map. It can conjunction with the keys(), values(), or entries() methods of a Map object to create an array containing the map’s keys, values, or key-value pairs, respectively.

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

// Convert map keys to an array
const keysArray = Array.from(map.keys());

// Convert map values to an array
const valuesArray = Array.from(map.values());

// Convert map entries (key-value pairs) to an array
const entriesArray = Array.from(map.entries());

console.log(keysArray);
console.log(valuesArray);
console.log(entriesArray);

Output

[ 'key1', 'key2', 'key3' ]
[ 'value1', 'value2', 'value3' ]
[ [ 'key1', 'value1' ], [ 'key2', 'value2' ], [ 'key3', 'value3' ] ]

Method 2: Using the Spread operator(…) and Map.keys()

The spread operator (…) in JavaScript allows you to expand an iterable, such as an array or a Map, into its elements. For example, when used with a Map object, it can be combined with the keys(), values(), or entries() methods to create a new array containing the map’s keys, values, or key-value pairs, respectively.

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

// Convert map keys to an array
const keysArray = [...map.keys()];

// Convert map values to an array
const valuesArray = [...map.values()];

// Convert map entries (key-value pairs) to an array
const entriesArray = [...map.entries()];

console.log(keysArray);
console.log(valuesArray);
console.log(entriesArray);

Output

[ 'key1', 'key2', 'key3' ]
[ 'value1', 'value2', 'value3' ]
[ [ 'key1', 'value1' ], [ 'key2', 'value2' ], [ 'key3', 'value3' ] ]

Method 3: Using for…of loop

  1. Create an empty array to store the keys.
  2. Use the for..of loop to iterate all the Map keys you will get from Map.keys() method.
  3. At each iteration, push that key into an empty array.
let myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);
myMap.set('c', 3);

let keysArray = [];
for (let key of myMap.keys()) {
  keysArray.push(key);
}

console.log(keysArray);

Output

[ 'a', 'b', 'c' ]

That’s it.