Javatpoint Logo
Javatpoint Logo

JavaScript Array flat() Method

The flat() method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array, and flats upto the specified depth. We can specify the depth limit to where we need to flatten the array. By default, the depth limit is 1.

Syntax

Parameters

Depth: It is an optional parameter which specifies the depth to flatten an array. By default, its value is 1.

Return

It returns a newly created array containing all the sub-array elements concatenated into it.

JavaScript Array flat() Method Example

Let's see the below examples to understand better.

Example1

A simple working of flat() method on a two dimensional array.

Test it Now

Output:

JavaScript Array flat() Method

Example2

Testing a multidimensional array with flat() method.

Test it Now

Output:

It is clear that each element in the array is concatenated to the newly created 1D array.

JavaScript Array flat() Method

Example3

Let's flatten an array upto a specified depth.

Test it Now

Output:

JavaScript Array flat() Method

Example4

Using flat() method with depth value as infinity.

Test it Now

Output:

JavaScript Array flat() Method

Example5

Let's flatten an array with holes in between.

Test it Now

Output:

JavaScript Array flat() Method

It is clear that all array elements are concatenated leaving the holes out, after applying the flat() method.


Next TopicJavaScript Array




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA