Underscore.JS - reduce method



Syntax

_.reduce(list, iteratee, [memo], [context])

reduce method reduces all values to a single value. It iterates over a given list of element, call the iteratee function which is bound to context object, if passed. Iteratee is called with three parameters: (memo, element, index, list). In case of JavaScript object, iteratee's object will be (memo, value, key, list). Returns the list for chaining purpose.

Memo is the first state of the reduction, and each successive step of it should be returned by iteratee. If no memo is passed to the initial invocation of reduce, then the first element is instead passed as the memo while invokee iteratee on the next element in the list.

Example

var _ = require('underscore');

//Example 1. get sum of each number of array
var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num }, 0);
console.log(sum);

//Example 2. get sum of each number of object
sum = _.reduce({one: 1, two: 2, three: 3}, function(memo, num) { return memo + num }, 0);
console.log(sum);

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

Command

\>node tester.js

Output

6
6
underscorejs_iterating_collection.htm
Advertisements