JavaScript Array flat()

Definition and Usage

flat() Method used to concatenate the elements of the sub-array to a new array.

See Also:

Array map() Method

Array flatMap() Method

Array filter() Method

Array forEach() Method

Example

Example 1

Create a new array and concatenate the elements of the sub-array:

const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();

Try It Yourself

Example 2

For multi-layered nested arrays, you can specify the expansion depth:

const myArr = [1, 2, [3, [4, 5, 6], 7], 8];
const newArr = myArr.flat(2);

Try It Yourself

Syntax

array.flat(depth)

Parameter

Parameter Description
depth Optional. Specify the depth to expand nested arrays. The default value is 1.

Return Value

Type Description
Array The new array after expansion.

Browser Support

Since January 2020, all modern browsers support JavaScript arrays flat() Method:

Chrome Edge Firefox Safari Opera
Chrome 69 Edge 79 Firefox 62 Safari 12 Opera 56
September 2018 January 2020 September 2018 September 2018 September 2018