JavaScript’s Array.reduce
method is an underrated little method. Along with Array.map
and Array.filter
, 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.map
maps values in one array to computed values in anotherArray.reduce
reduces values in one array into one value.
To run Array.reduce
, you’ll need:
- an array
- a function that takes arguments of
(previousValue, currentValue)
and returns a new value. - the
initialValue
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
- the ingredients
- a function that combines the current mixture with the next ingredient
- a glass
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…
(live examples of these working)