Array. prototype. reduce()
Reduces the whole array to a single value, such as a sum, an object, or a new array.
- Returns
- The final value of the accumulator.
- Changes the original
- No
Example
#const cart = [
{ name: 'HTML course', price: 49 },
{ name: 'CSS course', price: 59 },
{ name: 'JS course', price: 79 }
]
const total = cart.reduce((sum, item) => sum + item.price, 0)
console.log(total)Definition and usage
#The reduce() method walks through the array and, at every step, combines the current element with the result so far, called the accumulator. At the end it returns the final value of the accumulator.
That lets you compute a sum or average, group elements into an object, flatten an array, or build a count of occurrences. It’s the most versatile array method.
Always pass a starting value as the second argument. Without it, reduce() uses the first element as the starting point, and throws an error on an empty array.
Syntax
#array.reduce(callbackFn)
array.reduce(callbackFn, initialValue)Parameters
#callbackFn
function (accumulator, element, index, array)
The function that combines the accumulator with the current element. Its result becomes the new accumulator.initialValue
optional
The accumulator’s starting value, for example0,[], or{}.
More examples
#const answers = ['A', 'C', 'A', 'B', 'A', 'C']
const counts = answers.reduce((acc, answer) => {
acc[answer] = (acc[answer] ?? 0) + 1
return acc
}, {})
console.log(counts)const points = [80, 95, 70]
const average = points.reduce((sum, p) => sum + p, 0) / points.length
console.log(average)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- If
reduce()starts to look unreadable, a plainfor...ofloop can be a better choice. - For grouping elements, newer browsers have
Object.groupBy(), which reads more clearly than a hand-rolledreduce().
Related entries
#- Array.prototype.map()Creates a new array with the results of calling a function for every element.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
- Array.prototype.forEach()Calls a function for every element of the array.
- Object.groupBy()Groups elements by a key returned from a function.
Spotted a mistake or missing an example? Write to us.