# 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

`let newArray = array.flat(depth level);`

## Example

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

`let 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:

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

## Example

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

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

The code execution result:

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

## Example

Let's set a depth level:

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

The code execution result:

`['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`:

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

The code execution result:

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

## See also

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

← →
↑
en ru