JavaScript Reduce Method
Anatomy TODO THIS IS WRONG
[1, 2, 3] // An array (or any type)
.reduce( // method name
item, // single array element
index, // current elemet index
() => {} // function to be sequentially applied to each element (must return a result)
)
Basic example
const costs = [29.75, 41.84, 46.5]
const sum = costs.reduce((total, amount) => total + amount)
console.log(sum) // 118.09
But there’s more
The callback function can have upto 4 parameters.
const costs = [29.76, 41.85, 46.5];
const average = costs.reduce((total, amount, index, array) => {
total += amount;
if( index === array.length-1) // If we're done return the average
{
return total/array.length
} else {
return total // Otherwise, the existing total
}
})
Further simplified
const calculateAverage = (total, amount, index, array) => {
total += amount;
if( index === array.length-1) // If we're done return the average
{
return total/array.length
} else {
return total // Otherwise, the existing total
}
}
const costs = [29.76, 41.85, 46.5];
const average = costs.reduce(calculateAverage)
console.log(average)
From MDN
callback
Function to execute on each element in the array, taking four arguments:
accumulator
The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
currentValue
The current element being processed in the array.
currentIndex Optional
The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
array Optional
The array reduce() was called upon.
initialValue Optional
Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.
NOTE: If initialValue
isn’t provided, reduce()
will execute the callback function starting at index 1, skipping the first index. If initialValue
is provided, it will start at index 0.
If the array is empty and no initialValue is provided, TypeError
will be thrown. If the array has only one element (regardless of position) and no initialValue
is provided, or if initialValue
is provided but the array is empty, the solo value will be returned without calling callback
.