How to convert Map Values to an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Autri Taheri

Convert Map Values to an Array #

To convert the values of a Map to an array:

  1. Call the values() method on the Map to get an iterator object that contains all of the values in the Map.

  2. Call the Array.from() method, passing it the iterator as a parameter. The Array.from method creates a new array from an iterable object.

index.js
const map = new Map(); map.set('name', 'John'); map.set('age', 30); const values = Array.from(map.values()); console.log(values); // ๐Ÿ‘‰๏ธ ['John', 30] console.log(values.length); // ๐Ÿ‘‰๏ธ 2

We used the Map.values method to get an iterator object containing the values of the Map.

We passed the iterator as the only parameter to the Array.from method.

The Array.from method converts the iterable into an array and returns the new array instance.

This is the recommended approach when using TypeScript, because the compiler often complains when using the spread operator (...) with iterators.

An alternative approach is to use the spread operator (...).

Convert Map Values to an Array using spread operator #

To convert the values of a Map object to an array:

  1. Call the values() method on the Map to get an iterator object that contains the values of the Map.
  2. Use the spread operator (...) to unpack the values from the iterator into a new array.
index.js
const map = new Map(); map.set('name', 'Tom'); map.set('age', 39); const values = [...map.values()]; console.log(values); // ๐Ÿ‘‰๏ธ ['Tom', 39] console.log(values.length); // ๐Ÿ‘‰๏ธ 2

We used the spread operator (...) to include all of the values of the Map into a new array.

This is the most commonly used approach when converting the values of a Map into an array.

You can also do this with multiple Maps.

index.js
const map1 = new Map(); map1.set('name', 'Tom'); const map2 = new Map(); map2.set('country', 'Chile'); const values = [...map1.values(), ...map2.values()]; console.log(values); // ๐Ÿ‘‰๏ธ ['Tom', 'Chile'] console.log(values.length); // ๐Ÿ‘‰๏ธ 2

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee