Flatten an Array of Arrays in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 11, 2022

banner

Photo from Unsplash

Flatten an Array of Arrays in TypeScript #

Use the flat() method to flatten an array in TypeScript, e.g. const flat = arr.flat(). 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'], ['e', 'f'], ]; // 👇️ const flat: string[] const flat = arr.flat(); // 👇️ ['a', 'b', 'c', 'd', 'e', 'f'] console.log(flat);

If you are getting 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.

Because we didn't pass a value for the parameter, it defaults to 1.

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

index.ts
const arr = [[['a', 'b']], [['c', 'd']]]; // 👇️ const flat1: string[][] const flat1 = arr.flat(1); // 👇️ [['a', 'b'], ['c', 'd']] console.log(flat1); // 👇️ const flat2: string[] const flat2 = arr.flat(2); // 👇️ ['a', 'b', 'c', 'd'] console.log(flat2);

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

index.ts
const arr = [[[['a', 'b']]], [[['c', 'd']]]]; // 👇️ const flat: string[] 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.

Note that the inferred type of the flattened array might not be what you expect, in which 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);

If you don't like the flat() method, you can use forEach() to flatten an 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']

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 1 level.

The reduce() method can also be used in a similar way.

index.ts
const arr = [['a'], ['b', 'c'], ['d']]; // 👇️ const flat: string[] const flat = arr.reduce((accumulator, array) => { return [...accumulator, ...array]; }, []); console.log(flat); // 👉️ ['a', 'b', 'c', 'd']

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 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.