JavaScriptArrays

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
On this page

Example

#
JavaScript
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)
Console
187

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

#
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 example 0, [], or {}.

More examples

#
Counting occurrences
JavaScript
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)
Console
{ A: 3, C: 2, B: 1 }
Average
JavaScript
const points = [80, 95, 70]
const average = points.reduce((sum, p) => sum + p, 0) / points.length
console.log(average)
Console
81.66666666666667

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 plain for...of loop can be a better choice.
  • For grouping elements, newer browsers have Object.groupBy(), which reads more clearly than a hand-rolled reduce().

Related entries

#

Spotted a mistake or missing an example? Write to us.