.reduce()
is used calculate a single value based on the array
A reducer function (that you provide) is called on each element of the array and results in a single output value
Often used to perform a calculation that accepts all the elements of an array (usually numbers) as inputs
.reduce()
accepts the following parameters
The callback function (also referred to the reducer function in this case) for .reduce()
accepts the following parameters:
accumulator
: (required) the accumulated value previously returned in from the last iteration;
currentValue
: (required) current element being processed in the array.
index
: (optional) index of the current element being processed in the array
array
: (optional) the array map was called upon
initialValue
: (optional) the value to use as the first argument to for the first iteration of reduce()
; If no initialValue
is supplied, the first element in the array will be used
Using traditional (ES5) function syntax
const value = arr.reduce(function(previousValue, item, index, array) {
// ...
}, [initial]);
Using arrow syntax (ES6)
const value = arr.reduce((previousValue, item, index, array) => {
// ...
}, [initial]);
initialValue
is suppliedconst numbers = [1, 2, 3, 4, 5]
const result = numbers.reduce((sum, currentNumber) => {
return sum + currentNumber
})
console.log(result) // 15
initialValue
to 10const numbers = [1, 2, 3, 4, 5]
const result = numbers.reduce((sum, currentNumber) => {
return sum + currentNumber
}, 10)
console.log(result) // 25
Use .reduce()
to calculate the sum of the numbers found in the amounts
array; Save the result in a variable declared with const
called total