JavaScript Array reduce() Method
The array.reduce(function(total, currentValue, currentIndex, array), initialValue) method in JavaScript executes the given function on per element of the array and returns the "accumulated" result. This is one of the most complex methods for working with arrays. The Array.reduce() method is more flexible; its purpose is to take an array and compress its contents into a single value. The reduce() method calculates a single value from an array and applies the callback function to each array element in turn, from left to right, while storing the intermediate result.
Where:
- function: a callback function that will be executed once for each array element in ascending index order. The function takes the following parameters:
- total: acts as a return accumulator and matches the previously returned value of the callback function. The first time the callback function is called, the sum equals initialValue if one was provided or the first value in the array otherwise
- currentValue: the value of the current element
- currentIndex (optional): array index of the current element. It starts at index 0 if initialValue is specified, otherwise at index 1
- array (optional): the array to which the current element belongs (which is being traversed)
- initialValue (optional): the value used as the first argument of the first call for the callback function. If no initial value is specified, then the first element of the array will be used.
How to reduce an array from right to left?
You can use the reduceRight() method to call the callback in descending index order (right-to-left).