4.17.11
3.10.1
2.4.2
1.3.1
_.reduce(collection, [iteratee=_.identity], [accumulator])
Reduces collection
to a value which is the accumulated result of running
each element in collection
thru iteratee
, where each successive
invocation is supplied the return value of the previous. If accumulator
is not given, the first element of collection
is used as the initial
value. The iteratee is invoked with four arguments:
(accumulator, value, index|key, collection).
Many lodash methods are guarded to work as iteratees for methods like
_.reduce
, _.reduceRight
, and _.transform
.
The guarded methods are:
assign
, defaults
, defaultsDeep
, includes
, merge
, orderBy
,
and sortBy
Since
0.1.0
Arguments
argument
collection
[iteratee=_.identity]
[accumulator]
type
(Array|Object)
Function
*
description
The collection to iterate over.
The function invoked per iteration.
The initial value.
Returns
(array)
Example
_.reduce(
[1, 2],
function (sum, n) {
return sum + n;
},
0
);
// => 3
_.reduce(
{ a: 1, b: 2, c: 1 },
function (result, value, key) {
(
result[value] ||
(result[value] = [])
).push(key);
return result;
},
{}
);
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
_.reduce(
[1, 2],
function (sum, n) {
return sum + n;
},
0
);
// => 3
_.reduce(
{ a: 1, b: 2, c: 1 },
function (result, value, key) {
(result[value] || (result[value] = [])).push(key);
return result;
},
{}
);
// => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)