Array API during the latest years is becoming more and more powerful, there are a lot of useful functions that we can rely on every day, but one that has many use cases when transforming arrays into other types: objects, strings, numbers and you continue naming them.
Simple Example
First, let's see how the method is composed:
And now how the callback method is implemented:
const list = [{ name: 'joe', lemons: 2 }, { name: 'sara', lemons: 5 }];
const total = list.reduce( (accumulator, currentValue, index) => {
return accumulator + currentValue.lemons;
}, 0)
// total now is 7
- accumulator: On the first iteration, the accumulator contains the value we provided as initial value, but subsequent iterations will be the value we returned on each iteration, in this sample, the code is accumulating lemons count.
- currentValue: is the current iteration value coming from the array
- index*: in this scenario, we don't need the current iteration index, but just in case FYI.
In the body of the callback we just add the currentValue lemons to the accumulator.
And finally, the list reduce
gave us a number value.
Array to Object Example
Let's imagine code needs to count the values of different categories, so output instead of a single number, is going to return a map of the all the categories counts:
const list = [{ name: 'joe', lemons: 2, oranges: 1 }, { name: 'sara', lemons: 5, oranges: 2 }];
const totals = list.reduce( (accumulator, currentValue, index) => {
return {
lemons: accumulator.lemons + currentValue.lemons,
oranges: accumulator.oranges + currentValue.oranges
}
}, { lemons: 0, oranges: 0 })
// total now is { lemons: 7, oranges: 3 }