How to Flatten an Array of Arrays in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
3 min

banner

# Flatten an Array of Arrays in TypeScript

Use the flat() method to flatten an array in TypeScript.

The flat method takes a parameter, which defaults to 1 and indicates how deep the nested array should be flattened. The method returns a new array with the sub-array elements concatenated into it.

index.ts
const arr = [['a'], ['b', 'c'], ['d']]; const flat = arr.flat(); console.log(flat); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

flatten array of arrays in typescript

The code for this article is available on GitHub

If you get an error that "Property 'flat' does not exist on type", you have to add es2019 to the lib array in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { // ... other options "lib": [ // ... other libs "es2019" ] } }

We used the Array.flat() method to flatten an array.

The only parameter the method takes is the depth level to which the array should be flattened.

We didn't pass a value for the parameter, so it defaults to 1.

If your array is more deeply nested and you leave the default depth value of 1, the array won't get flattened completely.

index.ts
const arr = [[['a']], [['b', 'c']], [['d']]]; // โœ… 1 Level const flat1 = arr.flat(1); // ๐Ÿ‘‰๏ธ [ ['a'], ['b', 'c'], ['d'] ] console.log(flat1); // โœ… 2 Levels const flat2 = arr.flat(2); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd'] console.log(flat2);

flattening deeply nested arrays

If you don't know how deeply nested your array is and you want to flatten it completely, pass Infinity as an argument to the flat() method.

index.ts
const arr = [[['a']], [['b', 'c']], [['d']]]; const flat = arr.flat(Infinity); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd'] console.log(flat);

Passing Infinity to the flat method flattens the array to a single level.

# The inferred type of the flattened array might not be correct

Note that the inferred type of the flattened array might not be what you expect, in this case, you can use a type assertion.

index.ts
const arr = [[[['a', 'b']]], [[['c', 'd']]]]; // ๐Ÿ‘‡๏ธ const flat: string[] const flat1 = arr.flat(Infinity) as string[]; // ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] console.log(flat1);

inferred type of flattened array might not be correct

The code for this article is available on GitHub

# Flatten an Array in TypeScript using forEach()

This is a three-step process:

  1. Initialize a new variable to an empty array.
  2. Use the forEach() method to iterate over the array of arrays.
  3. On each iteration, unpack the values of the sub-array and push them into the new array.
index.ts
const arr = [['a'], ['b', 'c'], ['d']]; const flat: string[] = []; arr.forEach((array) => { flat.push(...array); }); console.log(flat); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

flatten array using foreach

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

On each iteration, we use the spread syntax and the push method to unpack the values of the sub-array and push them into the new array.

After the last iteration, the flat variable contains an array that has been flattened to 1 level.

I've also written a guide on how to use the flatMap method in TS.

# Flatten an Array in TypeScript using reduce()

This is a two-step process:

  1. Use the reduce() to iterate over the array.
  2. On each iteration, use the spread syntax to unpack the values of the accumulated array and the sub-array into a new array.
index.js
const arr = [['a'], ['b', 'c'], ['d']]; const flat = arr.reduce((accumulator, array) => { return [...accumulator, ...array]; }, []); console.log(flat); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']
The code for this article is available on GitHub

The function we passed to the reduce() method gets called for each element (sub-array) in the array.

We set the initial value for the accumulator variable to an empty array.

On each iteration, we unpack the values from the accumulator and the current sub-array into a new array and return the result.

The final result is an array that has been flattened to 1 level.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev