Reduce Explanation

I noticed reduce has been explained on the forum. But I want to make sure I am understanding it properly. Let us take this simple example:

var numbers = [65, 44, 12, 4];

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}

So we have an array of ‘numbers’ and a function (getSum) that takes 1 parameter (total), and 1 parameter (num). The getSum function returns the addition of both parameters. The myFunction is where things get interesting. Reduce is invoked (not sure if that is the proper term) on the numbers array. The beauty of the reduce function is that it can iterate over the whole array. The part that gets a little iffy for me is passing in the getSum (in javascript you can pass functions in as parameters ----mmmkay just go with it right?). Since getSum needs a total and a num to operate, I am assuming reduce must pass two parameters. For some reason, I think I am missing something or maybe I am drawing false conclusions. Maybe I don’t understand “callbacks”, as well as I think I do. I coded some in C++ and visual basic and the syntax is just peculiar to me.

Thanks for explaining it to me.

this

numbers.reduce(getSum);

is the same as

numbers.reduce(function(a, b) { return getSum(a, b); });

It might be helpful to you to stick with the latter; they are equivalent (it works the same as reduction in high-school algebra if you can remember that), but the latter is more explicit and easier to grok at the expense of more typing. To save yourself a few keystrokes:

numbers.reduce((a, b) => getSum(a, b));

might help if in a language you’re a bit more familiar with. If that’s helpful, also play around with LINQ (I think MS have a downloadable set of 100 or so examples in various languages, I’m drawing a blank on Google at the minute though). Note Aggregate is the equivalent of reduce in LINQ.

EDIT: I wrote this ages ago, it was an explanation of reduce for someone on the FCC chatrooms, might be useful: Explanation of how reduce works · GitHub

2 Likes