Summing an array
The most common example of application of .reduce(), usually seen in all textbooks and web pages, is summing all the elements of an array. So, in order to keep with tradition, let's start with precisely that example!
Basically, to reduce an array you must provide a dyadic function (that is, a function with two parameters; binary would be an another name for that) and an initial value. In our case, the function will sum its two arguments. Initially, the function will be applied to the provided initial value and the first element of the array, so for us the first result we have to provide is a zero, and the first result will be the first element itself. Then, the function will be applied again, this time to the result of the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access