Underscore is abbreviated, note

According to the underscore-reduce documentation, I need to pass three parameters.

For example:

var m = _.reduce([1,2,3], function (memo, num) {return (num * 2) +memo }, 0); m; // 12 as expected 

If I try to pass only the first two parameters, I get a different value. Why?

 var m = _.reduce([1,2,3], function (memo, num) {return (num * 2) +memo }); m; // 11 ..why? 
+7
source share
2 answers

With only two parameters passed to reduce , it will use the first and second elements of the array as arguments for the first function call.

 function addDouble(memo, num) {return (num * 2) +memo } [1,2,3].reduce(addDouble, 0) // is equivalent to addDouble(addDouble(addDouble(0, 1), 2), 3) [1,2,3].reduce(addDouble) // is equivalent to addDouble(addDouble(1, 2), 3) 

Usually you pass in the initial value, but many operations have the same result when you start without an identity element . For example:

 function add(a, b) { return a+b; } function double(a) { return 2*a; } [1,2,3].map(double).reduce(add) == [1,2,3].map(double).reduce(add, 0) 

See also docs for native reduce() .

+6
source

If you just pass two parameters, the original note will take the first value of the array, and the rest will pass. 11 = 1 + (2 * 2) + (3 * 3). that's why. And if you pass three parameters, then memo will take the third parameter as the initial menu and go through each element of the array.

0
source

All Articles