Friday, September 5, 2025
HomeLanguagesJavascriptLodash _.flattenDeep() and _.flattenDepth() Method

Lodash _.flattenDeep() and _.flattenDepth() Method

Lodash _.flattenDeep() Method

The _.flattenDeep() method is used to completely flatten nested arrays. It does this recursively.

Syntax:

_.flattenDeep( array )

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

  • array: This parameter holds the array that to be flatten.

Return Value: This method returns the new flattened array.

Example:




const _ = require('lodash');
  
let ar = [1, [2, [3, 4, [5]]]];
  
let flattenArray = _.flattenDeep(ar);
  
console.log(flattenArray);


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

[ 1, 2, 3, 4, 5 ]

Lodash _.flattenDepth() Method

The _.flattenDepth() method is used to flatten up to depth time that is passed into the function.

Syntax:

_.flattenDepth(array, depth)

Parameters: This method accepts two parameters as mentioned above and described below:

  • array: This parameter holds the array that need to be flatten.
  • depth: This parameter holds the maximum recursion depth.

Return Value: This method returns the new flattened array.

Example 1: Flatten to depth 1




const _ = require('lodash');
  
let ar = [1, [2, [3, 4, [5]]]];
  
let flattenArray = _.flattenDepth(ar, 1);
  
console.log(flattenArray);


Output:

[ 1, 2, [ 3, 4, [ 5 ] ] ]

Example 2: Flatten to depth 2




const _ = require('lodash');
  
let ar = [1, [2, [3, 4, [5]]]];
  
let flattenArray = _.flattenDepth(ar, 2);
  
console.log(flattenArray);


Output:

[ 1, 2, 3, 4, [ 5 ] ]

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference:

RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS