method is an underrated little method. Along with Array.map
it fits under the banner of ‘functional programming’, in that it lets you do
things you would do with for loops except with functions.
Array.mapmaps values in one array to computed values in another
Array.reducereduces values in one array into one value.
To run Array.reduce, you’ll need:
a function that takes arguments of (previousValue, currentValue) and
returns a new value.
Here’s sum implemented with reduce. The input array is [1, 2, 3], and
the function adds the running sum to the current value. The starting value
is 0. The neat part is that there’s a sort of feedback loop going: what
you return from the function is given back to it for the next element.
Reduce feels a lot to me like making juice: you have
a function that combines the current mixture with the next ingredient
Excruciating Technical Detail
Array.reduce is underrated because it can easily implement a lot of
other functions with just itself: the ‘single value’ it reduces into can be
anything: a number, and array, an object, and so on…