grokking reduce

62 views
Skip to first unread message

Dave Aronson

unread,
May 7, 2013, 8:44:04 AM5/7/13
to js-drip-d...@googlegroups.com
The name "reduce" gives a good clue to what it *does* (reduce an array to one value based on the whole thing).  However, to understand how it *works* is easier if you use Ruby's alternate name for it: inject.  It sort of "injects" the function between each consecutive pair of elements in the array.  At least, that's effectively what happens if you use something like simple addition.  So:

[1,2,3,4].reduce(function(prev,curr) { return prev + curr })

is equivalent to 1 + 2 + 3 + 4.  Unfortunately, this style doesn't make it quite so clear, but if you do something like:

add = function(prev,curr) { return prev + curr };
[1,2,3,4].reduce(add);

that makes it a bit clearer in the reduce call, just what you're doing.  (Especially if you declare add further away.)

-Dave

Joshua Clanton

unread,
May 8, 2013, 4:28:04 PM5/8/13
to js-drip-d...@googlegroups.com
That's a great point, Dave. "Inject" is much more descriptive of how it works. On the other hand, I think "reduce" is more descriptive of what it does. :-)

And I definitely endorse the idea of naming the callback functions to make them more explicit.

Joshua Clanton

Hugo Estrada

unread,
Jul 27, 2013, 2:03:14 PM7/27/13
to js-drip-d...@googlegroups.com


On Tuesday, May 7, 2013 8:44:04 AM UTC-4, Dave Aronson wrote:
this is probably the best explanation for reduce that I have read.  
Reply all
Reply to author
Forward
0 new messages