VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-array-flat-method/

⇱ JavaScript Array flat() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Array flat() Method

Last Updated : 15 Jul, 2025

The Javascript arr.flat() method was introduced in ES2019. The flat() method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. If no depth is provided, it defaults to 1.

Syntax:

arr.flat([depth])

Parameters:

This method accepts a single parameter as mentioned above and described below:

  • depth: It specifies, how deep the nested array should be flattened. The default value is 1 if no depth value is passed as you guess it is an optional parameter.

Return value:

It returns an array i.e. depth levels flatter than the original array, it removes nesting according to the depth levels.

Example 1:Flattening a Multilevel Array

The code initializes a multilevel array, then applies the flat() method with Infinity parameter to recursively flatten all nested arrays into a single-level array. The result is logged.


Output
[
 '1', '2', '3',
 '4', '5', '6',
 '7'
]

Example 2: Flattening Nested Arrays with flat() Method

The code demonstrates flattening a nested array to different levels using the flat() method. It applies flat() with various depth parameters (0, 1, 2) to flatten nested arrays accordingly and logs the results.


Output
Zero levels flattened array: 1,2,3,,4,5,6
One level flattened array: 1,2,3,,4,5,6
Two level flattened array: 1,2,3,4,5,6
Three levels flattened array: 1,2,3,4,5,6

Note: For depth greater than 2, the array remains the same, since it is already flattened completely. 

Example 3: Flattening an Array with undefined Element

This code creates an array arr with elements [1, 2, 3, empty, 4]. When flat() is called on arr, it removes the empty slot and creates a new flattened array newArr with elements [1, 2, 3, 4], which is then logged to the console.


Output
[ 1, 2, 3, 4 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

Comment