The Array.flat Method in JavaScript

Published: Friday, June 3, 2022

Greetings, friends! Have you ever had nested arrays and found yourself needing to flatten them?

javascript
Copied! ⭐️
// From this
const arrayWithNestedArrays = [['pancake', 'waffle'], ['pizza', 'potato']];

// To this
const arrayYouNeed = ['pancake', 'waffle', 'pizza', 'potato'];

The ECMAScript 2019 specification officially added the Array.flat method, so you can flatten arrays easily using native JavaScript code.

Here is the function definition for Array.flat:

javascript
Copied! ⭐️
flat()
flat(depth)

Looks like it accepts one optional parameter, depth. The depth defaults to a value of 1 if it isn't passed as an argument into the flat method.

Let's look an example of using the flat method without passing a depth.

javascript
Copied! ⭐️
const array = [['pancake', 'waffle'], ['pizza', 'potato']];

console.log(array.flat());
// OUTPUT: ['pancake', 'waffle', 'pizza', 'potato'];

That was easy! Let's look at another example that has even more nested arrays.

javascript
Copied! ⭐️
const arrayWith3Layers = [[[1, 2, 3]]];

In the example above, we have an array that has three layers. We have an array within an array within an array.

javascript
Copied! ⭐️
const arrayWith3Layers = [[[1, 2, 3]]];

const arrayWith2Layers = arrayWith3Layers.flat();
console.log(arrayWith2Layers); // [[ 1, 2, 3 ]]

const arrayWith1Layer = arrayWith2Layers.flat();
console.log(arrayWith1Layer); // [1, 2, 3]

Every time we call flat, we're "flattening" the array by a depth of 1, since that is the default value for depth when we pass nothing into the flat method.

Instead of calling flat() multiple times, we can specify how "deep" we want to flatten the original array.

javascript
Copied! ⭐️
const arrayWith3Layers = [[[1, 2, 3]]];

const arrayWith1Layer = arrayWith3Layers.flat(2);
console.log(arrayWith1Layer); // [1, 2, 3]

Internally, the flat method is recursively concatenating sub-array elements in an array. Below is an implementation of the flat method taken from MDN.

javascript
Copied! ⭐️
const array = [1, 2, [3, 4, [5, 6]]];

// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, depth = 1) {
  return depth > 0
    ? arr.reduce(
        (acc, val) =>
          acc.concat(Array.isArray(val) ? flatDeep(val, depth - 1) : val),
        []
      )
    : arr.slice();
}

const result = flatDeep(array, Infinity);
console.log(result); // [1, 2, 3, 4, 5, 6]

This implementation could be useful for creating our own flatDeep function in other programming languages that don't support it natively. Some languages only flatten arrays one layer and don't let you specify a depth. Therefore, you have to create your own function that recursively flattens an array down to a specified depth.

Resources