Open In App

Lodash _.flatMapDepth() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash's _.flatMapDepth() method flattens an array by applying a function to each element and recursively flattening the results up to a specified depth. It's similar to _.flatMap() but allows control over the flattening depth.

Syntax:

_.flatMapDepth( collection, iteratee, depth )

Parameters:

This method accepts three parameters as mentioned above and described below:

  • collection: It is the collection to iterate over.
  • iterate: It is the function that is invoked per iteration.
  • depth: It is a number that specifies the maximum recursion depth. It is an optional parameter. The default value is 1.

Return Value: This method returns the new flattened array.

Example 1: In this example we use Lodash's _.flatMapDepth() to duplicate each element in the users array, then recursively flatten the result to a depth of 2

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let users = ([3, 4]);

// Using the _.flatMapDepth() method
let flat_map = _.flatMapDepth(users, duplicate, 2)
function duplicate(n) {
    return [[[n, n]]];
}

// Printing the output 
console.log(flat_map);

Output:

[ [ 3, 3 ], [ 4, 4 ] ]

Example 2: In this example we use Lodash's _.flatMapDepth() to duplicate each string in the users array, recursively flattening the nested arrays to a depth of 2

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let users = (['q', 'r', 't', 'u']);

// Using the _.flatMapDepth() method
let flat_map = _.flatMapDepth(users, duplicate, 2)
function duplicate(n) {
    return [[[n, n]]];
}

// Printing the output 
console.log(flat_map);

Output:

[ [ 'q', 'q' ], [ 'r', 'r' ], [ 't', 't' ], ['u', 'u' ] ]

Next Article

Similar Reads