How to Convert a Map to an Array in TypeScript?

One of my team members asked about converting a map to an array in TypeScript. In this tutorial, I will explain how to convert a Map to an Array in TypeScript.

Maps and Arrays in TypeScript

Let us first understand what Maps and Arrays are in TypeScript.

What is a Map?

A Map is a collection of key-value pairs where each key is unique. Maps maintain the order of their elements, which makes them different from objects. They are particularly useful when you need to associate values with keys and retrieve them efficiently.

What is an Array?

An Array is a collection of elements indexed by a contiguous sequence of integers. Arrays are used to store multiple values in a single variable and can hold elements of any data type.

Why Convert a Map to an Array?

Converting a Map to an Array can be necessary for various reasons, such as:

  1. Data Manipulation: Arrays provide a plethora of methods for data manipulation, such as filter, map, reduce, etc.
  2. Interfacing with APIs: Many APIs expect data in array format.
  3. Simplified Iteration: Arrays are easier to iterate using loops and array methods.

Check out 2D Arrays in TypeScript

Convert a Map to an Array in TypeScript

There are several ways to convert a Map to an Array in TypeScript. Let’s explore each method with detailed examples.

Using Array.from()

The Array.from() method creates a new array from an iterable object in TypeScript. This method is efficient for converting a Map to an Array in TypeScript.

Example:

Here is an example.

const cityPopulationMap = new Map([
  ['New York', 8419000],
  ['Los Angeles', 3980000],
  ['Chicago', 2716000]
]);

const cityPopulationArray = Array.from(cityPopulationMap);
console.log(cityPopulationArray);

In this example, cityPopulationMap is a Map containing city names and their populations. Using Array.from(), we convert it into an array of key-value pairs.

Here is the exact output in the screenshot below:

Convert a Map to an Array in TypeScript

Check out Find an Object in a TypeScript Array

Using the Spread Operator

The spread operator (...) can also be used to convert a Map to a TypeScript Array. This method is concise and leverages the power of ES6 syntax.

Example:

Let me show you an example.

const stateCapitalMap = new Map([
  ['California', 'Sacramento'],
  ['Texas', 'Austin'],
  ['Florida', 'Tallahassee']
]);

const stateCapitalArray = [...stateCapitalMap];
console.log(stateCapitalArray);

Here, stateCapitalMap is converted into an array using the spread operator, resulting in an array of key-value pairs.

Here is the exact output in the screenshot below:

TypeScript Convert a Map to an Array

Using forEach()

The forEach() method can be used to iterate over the Map and push each entry into an array. This method provides more control and can be useful for custom transformations.

Example:

Let me show you an example.

const companyRevenueMap = new Map([
  ['Apple', 274500],
  ['Microsoft', 143000],
  ['Google', 182500]
]);

const companyRevenueArray: [string, number][] = [];
companyRevenueMap.forEach((value, key) => {
  companyRevenueArray.push([key, value]);
});
console.log(companyRevenueArray);

In this example, we use forEach() to iterate over companyRevenueMap and push each key-value pair into companyRevenueArray.

Convert Map Values to an Array

Sometimes, you may only need the values from the Map. You can achieve this using the values() method combined with Array.from() or the spread operator.

Example:

Here is an example.

const cityAreaMap = new Map([
  ['New York', 468.9],
  ['Los Angeles', 502.7],
  ['Chicago', 234.0]
]);

const cityAreas = Array.from(cityAreaMap.values());
console.log(cityAreas);

Here, we extract the values from cityAreaMap and convert them into an array using Array.from().

Convert Map Keys to an Array

Similarly, you might only need the keys from the Map. This can be done using the keys() method along with Array.from() or the spread operator.

Example:

Here is an example.

const stateAbbreviationMap = new Map([
  ['California', 'CA'],
  ['Texas', 'TX'],
  ['Florida', 'FL']
]);

const stateAbbreviations = [...stateAbbreviationMap.keys()];
console.log(stateAbbreviations);

In this example, stateAbbreviationMap keys are extracted and converted into an array using the spread operator.

Convert a Map to an Array in TypeScript Examples

Now, let me show you some examples of converting a map to an array in TypeScript.

Example-1: Data Visualization

Suppose you are working on a data visualization project where you need to display the population of various cities in a bar chart. The data is initially stored in a Map. To use this data with a charting library that requires an array, you need to convert the Map to an Array.

Example:

const cityPopulationMap = new Map([
  ['New York', 8419000],
  ['Los Angeles', 3980000],
  ['Chicago', 2716000]
]);

const cityPopulationArray = Array.from(cityPopulationMap);
const chartData = cityPopulationArray.map(([city, population]) => ({
  city,
  population
}));

console.log(chartData);

In this example, we convert the Map to an Array and then transform it into an array of objects suitable for the charting library.

Example-2: API Data Transformation

Suppose you are fetching data from an API that returns a Map of user IDs and their details. To display this data in a table, you need to convert the Map to an Array.

Example:

const userDetailsMap = new Map([
  [101, { name: 'John Doe', age: 30, city: 'New York' }],
  [102, { name: 'Jane Smith', age: 25, city: 'Los Angeles' }],
  [103, { name: 'Sam Brown', age: 22, city: 'Chicago' }]
]);

const userDetailsArray = Array.from(userDetailsMap, ([id, details]) => ({
  id,
  ...details
}));

console.log(userDetailsArray);

Here, we convert userDetailsMap into an array of user objects, making it easy to display in a table.

Conclusion

In this tutorial, I explained how to convert a Map to an array in TypeScript using different methods, such as using Array.from(), the spread operator, or forEach().