flat method

The flat method reduces the nesting level of a multidimensional array. It can either make an array one-dimensional or reduce the dimensionality by a given value.

Syntax

javascriptlet newArray = array.flat(depth level);

Example

Let's get a new array without specifying any value in the parameter:

javascriptlet arr = ['a', 'b', ['c', 'd']];
let res = arr.flat();

console.log(res);

As a result of executing the code, we will see that the subarrays have risen one level:

javascript['a', 'b', 'c', 'd']

Example

Now let's apply the flat method to an array with two levels of nesting:

javascriptlet arr = ['a', 'b', ['c', 'd', ['e', 'f']]];
let res = arr.flat();

console.log(res);

The code execution result:

javascript['a', 'b', 'c', 'd', ['e', 'f']]

Example

Let's set a depth level:

javascriptlet arr = ['a', 'b', ['c', 'd', ['e', 'f']]];
let res = arr.flat(2);

console.log(res);

The code execution result:

javascript['a', 'b', 'c', 'd', 'e', 'f']

Example

If we want not to bother with a level of nesting, but to merge the entire array, then we use the parameter Infinity:

javascriptlet arr = ['a', 'b', ['c', 'd', ['e', 'f', ['g', 'h', ['i']]]]];
let res = arr.flat(Infinity);

console.log(res);

The code execution result:

javascript[
  'a', 'b', 'c',
  'd', 'e', 'f',
  'g', 'h', 'i'
]

See also

  • the flatMap method
    that returns an array of elements after applying a function