How to Convert an Map to Array in JavaScript

To convert a Map to an Array in JavaScript, you can use the “spread operator(…)” or the “Array.prototype.from()” method.

Method 1: Using the Spread operator(…)

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.

Example

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 2: Using the Array.prototype.from() function

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. This method is beneficial when you need to convert different types of iterable objects to arrays or when you want to apply a mapping function to the elements of an iterable during the conversion process.

Example

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' ] ]

Both of these methods will give you the same results.

You can choose the method based on your requirements.

Leave a Comment