JavaScript Array flat()

Summary: in this tutorial, you’ll learn how to use the JavaScript Array flat() method to flat an array.

Introduction to the JavaScript Array flat() method

ES2019 introduced the Array.prototype.flat() method that creates a new array with all the elements of the subarrays concatenated to it recursively up to a specified depth.

The following shows the syntax of the flat() method:

let newArray = arrayObject.flat([depth])Code language: JavaScript (javascript)

The depth parameter specifies how deep the method flats the array structure. It defaults to 1.

The following example shows how to flat an array of numbers:

const numbers = [1, 2, [3, 4, 5]];
const flatNumbers = numbers.flat();

console.log(flatNumbers);Code language: JavaScript (javascript)

Output:

[1, 2, 3, 4, 5]Code language: JSON / JSON with Comments (json)

In this example, we didn’t pass the depth argument into the flat() method therefore the depth is 1 by default. The flat() method concatenated all the elements of the nested array [3,4,5] to the elements of the new array.

Note that the flat() method creates a new array and doesn’t change the original array:

console.log(numbers);Code language: JavaScript (javascript)

Output:

[ 1, 2, [ 3, 4, 5 ] ]Code language: JavaScript (javascript)

The following example flats an array with two level depth:

const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);

console.log(flatNumbers);Code language: JavaScript (javascript)

Output:

[1, 2, 3, 4, 5, 6, 7]Code language: JavaScript (javascript)

When you don’t know the depth level, you can pass the Infinity into the flat() method to recursively concatenate all elements of the sub-arrays into the new array:

const numbers = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];
const flatNumbers = numbers.flat(Infinity);

console.log(flatNumbers);Code language: JavaScript (javascript)

If an array has empty slots, you can use the flat() method to remove the holes, like this:

const numbers = [1, 2, , 4, , 5];
const sequence = numbers.flat();

console.log(sequence);Code language: JavaScript (javascript)

Output:

[ 1, 2, 4, 5 ]Code language: JavaScript (javascript)

Summary

  • Use the Array.prototype.flat() method to flat an array with the nested arrays.
  • Use the depth argument to specify how deep the nested arrays should be flattened. The depth is 1 by default.
  • The flat() also removes the holes in the array with empty slots.
Was this tutorial helpful ?