TypeScript Convert Array To Map

A typescript array allows you to hold elements of different types, and a map allows you to store key-value pairs of items. One of the common requirements in a typescript project is to convert an array to a map. In this post, we shall learn different ways to convert an array to a map in typescript easily.

Map Benefits

Map data types provide several benefits as compared to arrays, such as quicker lookups and accessing an element directly by providing the key. In addition, map data types maintain the order of insertion, so you can retrieve them in the same order as you insert.

TypeScript provides two ways to convert this.

  1. Array Map function
  2. Array Reduce function

Array Map function

The array map function allows us to create an array of key-value pairs. It accepts a callback function, and then we pass this array to a map constructor. Below is an example.

const arr = [
  { key: 'user1', value: { name: 'name 1', age: 23 } },
  { key: 'user2', value: { name: 'name 2', age: 34 } },
  { key: 'user3', value: { num: 'name 3', age: 45 } },
];

let result = new Map(arr.map(obj => [obj.key, obj.value]));
console.log(result.get("user1"));

//Result
{
  "name": "name 1",
  "age": 23
} 

In the above example, we have an array object named “arr” that contains objects. In the array map callback function, we return an array object with a key and value. We pass the returned array into the map data type constructor to convert the array to a map data type. In the last row, we use the get method of the map data type to get the user-1 value.

Array Reduce Method

The reduce method in typescript allows you to convert an array to a single output value. We can use the reduce method to convert an array to a map data type. Below is an example.

const arr = [
  { key: 'user1', value: { name: 'name 1', age: 23 } },
  { key: 'user2', value: { name: 'name 2', age: 34 } },
  { key: 'user3', value: { num: 'name 3', age: 45 } },
];

var result2 = arr.reduce((a, {key, value}) => a.set(key, value.age), new Map());

console.log(result2.get('user2'));

In the above example, we have used the reduce method. We pass new Map() in the second parameter as the initial value. In the first parameter, we pass two parameters. The first parameter, “a” is an accumulator and variable of the map, which is used to store results. The second parameter is the current value of the array, which is passed by the reduce method for calling the set method of the map.

Summary

To convert an array to a map in TypeScript, there are two options: 1) array map function; and 2) array reduce function.