Reputation: 451
I'm trying to solve this question: Use _.reduce to multiply all the values in an array.
Here's what I came up with:
var product = _.reduce([1, 2, 3], function(x, y){ return x * y; }, 0);
= 9
Is this close? I don't feel like I'm fulling grasping reduce(). Please help.
Upvotes: 1
Views: 233
Reputation: 339816
You should either omit the final 0
parameter from your call to _.reduce
, or replace it with 1
, depending on the semantics you want to achieve if you were to supply an empty array.
Rather than think of variables x
and y
in the callback, consider them as accumulator
and current
. In the first pass the "initial value" parameter is passed as accumulator
, and in each subsequent pass the result of the previous pass is supplied as accumulator
.
The 0
you erroneously supplied is passed as the first value of accumulator
, and therefore every subsequent multiplication also results in 0
.
Fortunately, the specification for reduce
says that if you omit that initial value parameter then it will take the first element of the supplied array to be in the initial value for accumulator
and then only iterate from the second element onwards.
If you don't supply an initial value then the array must have at least one element in it.
Upvotes: 1