Underscore.JS - reduceRight method



Syntax

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

reduceRight is the right-associative variant of reduce method to reduce 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');

var list = [[0], [1], [2], [3]]
//Example using reduce. prepare a single list of elements
var result = _.reduce(list, function(memo, element) { return memo.concat(element) }, []);
console.log(result);

//Example using reduceRight. prepare a single list of elements
result = _.reduceRight(list, function(memo, element) { return memo.concat(element) }, []);
console.log(result);

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

Command

\>node tester.js

Output

[ 0, 1, 2, 3 ]
[ 3, 2, 1, 0 ]
underscorejs_iterating_collection.htm
Advertisements