How Flattening Works in Lodash flatMap

The _.flatMap method in the Lodash JavaScript library maps each element of a collection through an iteratee function and then flattens the result by a single level. This article explores how this shallow flattening operation behaves, how it handles nested arrays, and how it compares to other Lodash flattening utilities such as _.flatMapDeep and _.flatMapDepth.

The Default Flattening Operation: Single-Level Flattening

When you use _.flatMap(collection, [iteratee=_.identity]), Lodash applies the iteratee to each item and then performs a shallow, one-level-deep flattening operation on the returned array. It functions identically to chaining a standard _.map followed by _.flatten.

This means that:

Example

const _ = require('lodash');

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

// Single-level flattening
const result = _.flatMap([1, 2], duplicate);
console.log(result);
// Output: [1, 1, 2, 2]

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

// Deeply nested results are only flattened by one level
const nestedResult = _.flatMap([1, 2], nestedDuplicate);
console.log(nestedResult);
// Output: [[1, 1], [2, 2]]

Comparison with Deep Flattening Operations

Because _.flatMap only reduces nesting by one level, deeply nested structures require alternative functions:

Native JavaScript Equivalence

The behavior of Lodash's _.flatMap mirrors the native ECMAScript Array.prototype.flatMap() method introduced in ES2019, which also applies a single-depth flatten (depth = 1) to the transformed collection.