Control Flattening Depth with Lodash flatMapDepth

The _.flatMapDepth method in Lodash allows developers to map over a collection and flatten the resulting array up to a specified recursion level. While methods like _.flatMap flatten results only one level deep and _.flatMapDeep flattens arrays completely, _.flatMapDepth provides precise control over the flattening process. This article demonstrates how the depth parameter functions, the syntax required, and how to control recursion depth with practical code examples.

Syntax and Parameters

The _.flatMapDepth method takes three arguments:

_.flatMapDepth(collection, [iteratee=_.identity], [depth=1])

How Recursion Depth Works

When the iteratee returns nested arrays, Lodash checks the depth argument to determine how many structural array layers to strip away.

Code Examples

Example 1: Default Depth (depth = 1)

By default, the function only unwraps the first layer of arrays returned by the iteratee:

const _ = require('lodash');

function duplicateAndNest(n) {
  return [[[n, n]]];
}

// Default depth is 1
const result = _.flatMapDepth([1, 2], duplicateAndNest);
console.log(result);
// Output: [ [ [ 1, 1 ] ], [ [ 2, 2 ] ] ]

Example 2: Explicit Recursion Depth

Increasing the depth integer flattens deeper arrays:

const _ = require('lodash');

function nestLevels(n) {
  return [[[n]]]; // 3 levels of array wrapping
}

// Flatten 2 levels deep
const depthTwo = _.flatMapDepth([5], nestLevels, 2);
console.log(depthTwo);
// Output: [ [ 5 ] ]

// Flatten 3 levels deep
const depthThree = _.flatMapDepth([5], nestLevels, 3);
console.log(depthThree);
// Output: [ 5 ]

Example 3: Zero Depth

Setting depth to 0 leaves the returned array structures untouched:

const _ = require('lodash');

const numbers = [10, 20];
const result = _.flatMapDepth(numbers, (n) => [[n]], 0);

console.log(result);
// Output: [ [[10]], [[20]] ]

Practical Application: Managing Hierarchical Data

Controlling depth is useful when working with tree structures, such as organizational charts or category trees, where you only want to expose immediate sub-nodes without unnesting the entire sub-tree:

const _ = require('lodash');

const categories = [
  { name: 'Tech', subcategories: [['Laptops'], ['Smartphones', ['Accessories']]] }
];

// Flattening only the first subcategory layer while preserving deeper groupings
const topSubcategories = _.flatMapDepth(categories, (cat) => cat.subcategories, 1);

console.log(topSubcategories);
// Output: [ 'Laptops', 'Smartphones', [ 'Accessories' ] ]

By adjusting the third argument in _.flatMapDepth, you can manipulate complex nested structures without executing multiple subsequent .flat() or .map() operations.