reduce() method executes a reducer function for array elements.
reduce() method returns a single value (can be a number, string, object, array).
syntax ↴
reduce(callbackFn, initialValue) A function to execute for each element in the array ↴
function is called with the following arguments ↴
reduce(function(accumulator, currentValue, currentIndex, array, initialValue)) ↴
accumulator contains the value calculated from the previous iteration.
On the first iteration, if an initialValue is provided, the accumulator will be set to the value of initialValue.
The accumulator parameter is the single value that will be returned by the reduce() method.
currentValue current value of the element being passed from the array.
currentIndex index of the element being passed from the array.
On the first call, currentIndex value is 0 if initialValue is specified, otherwise 1.
and callbackFn starts executing with the second value in the array as currentValue.
array original array on which the reduce() method was called.
initialValue (optional). If initialValue is not specified, accumulator is initialized to the first value in the array.
reduce() method returns the value that results from the reduction.
reduce() method does not execute the function for empty array elements.
reduce() method does not change the original array.
If no elements and initialValue is not provided TypeError is thrown.
myArray.reduce(callbackFn, initialValue)
books.reduce(callbackFn, initialValue)
// most popular books by Roald Dahl
const books = [
{ title: "Charlie and the Chocolate Factory", published: "1964", pages: 192, price: 5.59 },
{ title: "Fantastic Mr Fox", published: "1970", pages: 112, price: 5.79 },
{ title: "The BFG", published: "1982", pages: 194, price: 5.29 },
{ title: "Matilda", published: "1988", pages: 256, price: 5.49 },
{ title: "James and the Giant Peach", published: "1961", pages: 160, price: 5.89 },
{ title: "The Witches", published: "1983", pages: 224, price: 5.39 },
]