VOOZH about

URL: https://www.geeksforgeeks.org/javascript/lodash-_-flatmapdepth-method/

⇱ Lodash _.flatMapDepth() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lodash _.flatMapDepth() Method

Last Updated : 3 Sep, 2024

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

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

Output:

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