Create A Map From An Array In JavaScript

To create a map from an array in JavaScript, pass the two-dimensional array to the Map() constructor. The Map() constructor expects an array of arrays, with each sub-array having exactly two elements. The first element in each sub-array is used as the key, and the second element is used as the value.

Let’s discuss this in detail below.

create a map from an array in javascript

Create A Map From An Array In JavaScript

The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.

In order to create a map from an array, we need to pass the array to the Map() constructor. The Map() constructor expects an array of arrays, with each sub-array having exactly two elements. The first element in each sub-array is used as the key, and the second element is used as the value.

For example, consider the following array:

var arr = [['a', 1], ['b', 2], ['c', 3]];

We can create a map from this array by passing it to the Map() constructor:

var map = new Map(arr);

Let’s see how this works. We can access the keys and values of our map using the forEach() method –

var arr = [['a', 1], ['b', 2], ['c', 3]];

var map = new Map(arr);

map.forEach((value, key) => {

 console.log(key, value);

});

Output:

a, 1

b, 2

c, 3

As you can see, the first element in each sub-array is used as the key, and the second element is used as the value. You can also use the Map.prototype.get() method to access specific keys:

var arr = [['a', 1], ['b', 2], ['c', 3]];

var map = new Map(arr);

console.log(map.get('a')); // 1

console.log(map.get('b')); // 2

console.log(map.get('c')); // 3

You can also use the Map.prototype.has() method to check if a key exists in the map:

var arr = [['a', 1], ['b', 2], ['c', 3]];

var map = new Map(arr);

console.log(map.has('a')); // true

console.log(map.has('b')); // true

console.log(map.has('c')); // true

console.log(map.has('d')); // false

But, what if we have an array of objects? In that case, we have to use the map() method to convert the array of objects to an array of arrays as follows –

var arr = [{name: 'John', age: 30}, {name: 'Smith', age: 35}, {name: 'Jane', age: 28}];

var map = new Map(arr.map(item => ([item.name, item.age])));

map.forEach((value, key) => {

 console.log(key, value); 

});

Output

“John”, 30

“Smith”, 35

“Jane”, 28

As you can see, the map() method takes care of converting our array of objects to an array of arrays.

And that’s how you can create a map from an array in JavaScript. You can use the Map() constructor to create a map from an array of arrays, with each sub-array having exactly two elements. The first element in each sub-array is used as the key, and the second element is used as the value. If you have an array of objects, you can use the map() method to convert the array of objects to an array of arrays.

I hope this article was helpful. Thanks for reading!

Leave a Reply