Lodash - reduce method



Syntax

_.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).

Arguments

  • collection (Array|Object) − The collection to iterate over.

  • [iteratee=_.identity] (Function) − The function invoked per iteration.

  • [accumulator] (*) − The initial value.

Output

  • (*) − Returns the accumulated value.

Example

var _ = require('lodash');
var list = [1, 2, 3, 4];
var result = _.reduce(list, function (sum, n) {
   return sum + n;
}, 0);
console.log(result);

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

10
lodash_collection.htm
Advertisements