How Lodash flatMap Handles Boolean Primitives

When using the Lodash _.flatMap method on collections where the iteratee returns strictly boolean primitives, the method preserves the boolean values without altering, coercing, or discarding them. Because _.flatMap maps elements and then flattens the result by a single depth level, non-array values—such as true and false—are treated as non-flattenable elements and are retained directly in the final output array.

The Mechanism Behind _.flatMap

In the Lodash library, _.flatMap(collection, iteratee) operates as a composition of _.map followed by a single-level flatten (_.flatten).

The process unfolds in two distinct steps:

  1. Mapping: The provided collection is iterated over, and each item is passed to the iteratee function. If the iteratee returns a primitive boolean, the intermediate mapped array contains pure boolean values (for example, [true, false]).
  2. Flattening: Lodash evaluates each item in the mapped array using an internal isFlattenable check. This check verifies whether an item is an array or an arguments object.

Primitives, including booleans, numbers, and strings, fail the isFlattenable test. Consequently, Lodash leaves the primitive boolean values untouched rather than attempting to iterate over or spread them.

Practical Examples

Consider an operation where the iteratee evaluates conditions that produce boolean primitives:

const _ = require('lodash');

const numbers = [1, 2, 3, 4];
const result = _.flatMap(numbers, (n) => n % 2 === 0);

console.log(result);
// Output: [false, true, false, true]

Even if the input contains a mixture of nested arrays containing booleans and raw boolean primitives, only the array wrappers are dissolved:

const mixed = [[true], false, [false, true]];
const result = _.flatMap(mixed, (item) => item);

console.log(result);
// Output: [true, false, false, true]

In this scenario:

Key Takeaways