According the documentation underscore-reduce I should 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 just 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?
With only two parameters passed into reduce
, it will use the first and second array items as arguments to 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 will pass the start value, but many operations have the same result when starting without their 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 the docs for native reduce()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With