How to Create a Map from an Array in TypeScript?

I recently got a situation where I needed to efficiently transform an array of key-value pairs into a Map. In this tutorial, I will explain how to create a Map from an array in TypeScript.

The Map Data Structure in TypeScript

Let me first explain what a Map is in TypeScript. A Map is a built-in data structure that allows you to store key-value pairs, where each key is unique. It provides an efficient way to retrieve values based on their corresponding keys. Maps are particularly useful when you need to look up values by their keys quickly or when you have a large dataset to manage.

Create a Map from an Array in TypeScript

To create a Map from an array in TypeScript, you can utilize the Map constructor along with the Array.map() method. The Array.map() method creates a new array by calling a provided function on every element in the original array.

Here’s an example of how to create a Map from an array of key-value pairs:

const employeeData = [
  ['John Doe', 'Software Engineer'],
  ['Jane Smith', 'Product Manager'],
  ['Mike Johnson', 'Sales Representative'],
];

const employeeMap = new Map(employeeData.map(([name, position]) => [name, position] as [string, string]));

In this example, we have an array employeeData that contains employee names and their corresponding positions. We use the Array.map() method to transform each element of the array into a key-value pair suitable for the Map constructor.

The as [string, string] type assertion is used to ensure that the resulting array elements are of type [string, string], matching the expected type for Map initialization. Finally, we create a new Map instance using the transformed array.

Check out 2D Arrays in TypeScript

Access Values from the Map in TypeScript

Once you have created a Map from an array in TypeScript, you can easily access the values using the get() method. Here’s an example:

console.log(employeeMap.get('John Doe')); // Output: Software Engineer
console.log(employeeMap.get('Jane Smith')); // Output: Product Manager

The get() method takes a key as an argument and returns the corresponding value associated with that key. If the key doesn’t exist in the Map, undefined will be returned.

Here is the complete code:

const employeeData = [
    ['John Doe', 'Software Engineer'],
    ['Jane Smith', 'Product Manager'],
    ['Mike Johnson', 'Sales Representative'],
  ];
  
  const employeeMap = new Map(employeeData.map(([name, position]) => [name, position] as [string, string]));
  console.log(employeeMap.get('John Doe')); // Output: Software Engineer
  console.log(employeeMap.get('Jane Smith')); // Output: Product Manager

Here is the exact output in the screenshot below:

Create a Map from an Array in TypeScript

Read Find an Object in a TypeScript Array

Update and Add Values to the Map in TypeScript

You can update or add new key-value pairs to the Map using the set() method in TypeScript. Here’s an example:

employeeMap.set('John Doe', 'Senior Software Engineer');
employeeMap.set('Sarah Wilson', 'Marketing Coordinator');

In this example, we update John Doe’s position to “Senior Software Engineer” and add a new employee, Sarah Wilson, with the position “Marketing Coordinator”.

Remove Values from the Map in TypeScript

To remove a key-value pair from the Map, you can use the delete() method. Here’s an example:

employeeMap.delete('Mike Johnson');

This will remove the key-value pair associated with the key “Mike Johnson” from the Map.

Iterate Over the Map in TypeScript

You can easily iterate over the key-value pairs of a Map using a for...of loop. Here’s an example:

for (const [name, position] of employeeMap) {
  console.log(`${name}: ${position}`);
}

This loop will iterate over each key-value pair in the employeeMap and log the employee name and position to the console.

Check out Calculate the Sum of an Array in TypeScript

Best Practices and Tips

When working with Maps in TypeScript, keep the following best practices and tips in mind:

  1. Use descriptive and meaningful key names to enhance code readability and maintainability.
  2. If you need to store complex objects as values in the Map, consider creating custom types or interfaces to ensure type safety.
  3. Take advantage of the has() method to check if a key exists in the Map before accessing its value to avoid potential errors.
  4. If you need to convert a Map back to an array, you can use the Array.from() method or the spread operator (...).

Conclusion

In this tutorial, I explained how to create a map from an array in TypeScript using the Map constructor and the Array.map() method.

You may also like: