I just started exploring the JavaScript Underscore library more in-depth and just want to clarify what I think _.reduce() (also known as inject and foldl) does is right. My question is: is the below right?
When _.reduce([1, 2, 3, 4, 5], function(memo, num) { return memo + num; }, 5); is called, the following happens:
memostarts at5memo+list[0]=memo=6memo+list[1]=memo=8memo+list[2]=memo=11memo+list[3]=memo=15memo+list[4]=memo=20
And that is why the ran function returns 20. Is that right? And therefore _.reduceRight() is the opposite and starts from memo + list[ /* last element in array */ ]?
Thanks.
Regards.
Yes, that’s correct. The first argument to the
reducecallback represents the value returned from the last iteration (or the seed when in the first iteration).The second argument to the callback is the value of the current iteration of the Array.
As such, the first argument is an accumulator of whatever result you’re trying to reach. The final value is returned from the
_.reducefunction when all iterations are complete.