Create a Map from an Array using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

banner

Photo by Claude Piché

Create a Map from an Array using JavaScript #

To create a Map from an array, pass a two dimensional array containing key-value pairs to the Map() constructor. The Map constructor creates a new Map and adds each key-value pair to it.

index.js
// ✅ from Array of ARRAYS const arr1 = [ ['name', 'Tom'], ['country', 'Chile'], ]; const map1 = new Map(arr1); console.log(map1); // 👉️ {'name' => 'Tom', 'country' => 'Chile'} // ✅ from Array of OBJECTS const arr2 = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; const map2 = new Map( arr2.map(object => [object.key, object.value]) ); console.log(map2); // 👉️ {'name' => 'Tom', 'country' => 'Chile'}

In our first example, we passed a two dimensional array containing key-value pairs directly to the Map() constructor. All key-value pairs got added to the new Map.

In the second code snippet, we have an array of objects. We know that the Map() constructor expects an array of arrays, so we have to somehow make the conversion.

We iterated over the array using the Array.map method.

The function we passed to the map method gets called with each element (object) in the array.

The Array.map() method returns a new array containing the values that the callback function returned.

On each iteration, we return an array containing the key and the value of the object.

index.js
const arr2 = [ {key: 'name', value: 'Tom'}, {key: 'country', value: 'Chile'}, ]; // 👇️ [ ['name', 'Tom'], ['country', 'Chile'] ] const twoDimensionalArr = arr2.map( object => [object.key, object.value] ); console.log(twoDimensionalArr)

Now we have an array of arrays that we can pass to the Map() constructor.

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