JavaScript flat()Method

Array 对象参考手册JavaScript Array Object

Example

Recursively traverse the array to a specified depth:

let nestedArray = [1, 2, [3, 4, [5, 6]]]; let flatArray = nestedArray.flat(); console.log(flatArray); //Output: [1, 2, 3, 4, [5, 6]] //Specify depth as 2 let deeplyNestedArray = [1, 2, [3, 4, [5, 6]]]; let deeplyFlatArray = deeplyNestedArray.flat(2); console.log(deeplyFlatArray); //Output: [1, 2, 3, 4, 5, 6]

The output result is:


Try it Yourself »

In the above example, the flat() method is used to flatten the nested array nestedArray into a one-dimensional array. In the second example, by passing a depth parameter, the nested array deeplyNestedArray can be deeply flattened.

Note that the flat() method returns a new array, and the original array is not affected.


Definition and Usage

The flat() method recursively traverses the array at a specified depth and merges all elements and the elements of sub-arrays encountered into a new array, which is returned.

The flat() method returns a new array containing all elements of the array and sub-arrays.

The flat() method recursively traverses the array, extracts all nested array elements, and generates a new one-dimensional array.


Browser Support

The numbers in the table indicate the first browser version that supports the method.

Method
flat() 45.0 12.0 32.0 9 25.0

Syntax

flat()
flat(depth)

Parameters

Parameter Description
depth Specifies the structural depth for extracting nested arrays, with a default value of 1.

Technical Details

Return value: Array.
JavaScript Version: ECMAScript 6

More Examples

Flatten nested arrays

Example

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

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

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

//Use Infinity to expand nested arrays of any depth
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Flattening and array holes:The flat() method removes empty slots in an array:

Example

var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]


Array 对象参考手册JavaScript Array Object

Other Extensions