Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript flat() Method

JavaScript flat() Method

Array Object Reference JavaScript Array object

Example

Recursively traverse an 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 is:

Try it »

In the example above, 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 deeply nested array deeplyNestedArray can be flattened to a greater depth.

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


Definition and Usage

The flat() method recursively traverses an array to a specified depth and merges all elements with the elements of the traversed sub-arrays into a new array that is returned.

The flat() method returns a new array containing all elements from the array and its 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 this method.

Method
flat() 45.0 12.0 32.0 9 25.0

Syntax


flat()
flat(depth)

Parameters

Parameters Description
depth Specifies the structural depth to extract nested arrays, with a default value of 1.

Technical Details

Return value: array.
JavaScript version: ECMAScript 6

More examples

Flatten a nested array

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]

// Using Infinity flattens 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 the array:

Example

var

arr4

=

[

1

,

2

,

,

4

,

5

]

;

arr4.

flat

(

)

;

// [1, 2, 4, 5]


Array Object Reference JavaScript Array object