Lodash reduce Supported Accumulator Types
The _.reduce function in the Lodash JavaScript library
is a versatile aggregation utility that supports any valid JavaScript
data type as an accumulator. Because JavaScript is dynamically typed,
_.reduce does not restrict the accumulator to a predefined
set of structures; developers can use primitive types such as numbers,
strings, and booleans, complex references like plain objects and arrays,
modern collections like Map and Set, or even
omit the accumulator entirely to rely on the first element of the
collection.
Primitive Types
- Numbers: The most common accumulator type for
arithmetic operations. A number is typically initialized to
0or1to calculate sums, products, averages, or counters. - Strings: Frequently initialized as an empty string
(
"") to concatenate values, format template strings, or build URL query parameters and serialized formats. - Booleans: Initialized to
trueorfalseto evaluate conditions across a dataset, serving as a flexible alternative to_.everyor_.some.
Object and Array Types
- Plain Objects (
{}): Highly common for grouping, indexing, or pivoting collections. An empty object accumulator allows transforming an array of items into a lookup table indexed by a specific property ID or creating a frequency distribution map. - Arrays (
[]): Used when the output must be an ordered list. Using an array accumulator enables filtering, mapping, and flattening simultaneously in a single iteration pass, avoiding intermediate array allocations.
ES6 Collections
Map: Ideal when keys are dynamic, non-string types, or when frequent insertions and lookups require the performance guarantees of a hash map.Set: Used when collecting unique elements across a nested or duplicated data structure, ensuring all aggregated entries are distinct without manual deduplication logic.
Custom and Advanced Types
- Class Instances: Custom instances can accumulate state, trigger internal validation, or run domain-specific methods during each iteration step.
- Functions and Promises: Accumulators can be function pipelines (composing multiple functions) or promise chains to execute asynchronous tasks sequentially across an array of items.
Omitted Accumulator (Default Behavior)
If the accumulator argument is omitted or passed as
undefined, Lodash uses the first element of the collection
as the initial accumulator value, and iteration begins with the second
element. This behavior is standard for mathematical reductions like
finding the maximum value (Math.max) or cumulative string
joins where a separate seed value is unnecessary.