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:
- If the iteratee returns a one-dimensional array
[x, y], the elements are unpacked directly into the parent array. - If the iteratee returns an already nested array such as
[[x, y]], only the outermost array is stripped, leaving[x, y]intact.
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:
_.flatMapDeep: Flattens mapped results recursively until no nested arrays remain (depth of infinity)._.flatMapDepth: Accepts a third parameter specifying the exact numeric depth to flatten the results (e.g.,_.flatMapDepth(collection, iteratee, 2)).
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.