Array.prototype.flat()

The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Syntax

flat()
flat(depth)

Parameters

depth (optional)
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Return value

A new array with the sub-array elements concatenated into it.

Examples

Flattening nested arrays

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

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

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

Specifications

See ECMA-262, Array.prototype.flat.