Last updated: Feb 28, 2024
Reading timeยท3 min

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.
const arr = [['a'], ['b', 'c'], ['d']]; const flat = arr.flat(); console.log(flat); // ๐๏ธ ['a', 'b', 'c', 'd']

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.
{ "compilerOptions": { // ... other options "lib": [ // ... other libs "es2019" ] } }
We used the Array.flat() method to flatten an array.
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.
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);

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.
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.
Note that the inferred type of the flattened array might not be what you expect, in this case, you can use a type assertion.
const arr = [[[['a', 'b']]], [[['c', 'd']]]]; // ๐๏ธ const flat: string[] const flat1 = arr.flat(Infinity) as string[]; // ๐๏ธ ['a', 'b', 'c', 'd'] console.log(flat1);

This is a three-step process:
forEach() method to
iterate over the array of
arrays.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 to 1 level.
I've also written a guide on how to use the flatMap method in TS.
This is a two-step process:
reduce() to iterate over the array.const arr = [['a'], ['b', 'c'], ['d']]; 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.
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.