How to Use the Reduce Method in JavaScript

Turning an array into a single value with reduce in JavaScript.

There are times when you need to turn an array into a single value, like adding up the total of a shopping cart or counting how many times something shows up. The reduce method handles all of these, and once it clicks you'll find uses for it everywhere.

The reduce() method runs a callback on every item in an array and carries the result along, reducing the array down to one value.

How reduce Works

reduce takes a callback and an initial value:

const result = arr.reduce((accumulator, currentValue, index, array) => {
// return the new accumulator
}, initialValue)

The accumulator is the running result. It starts as initialValue, and whatever your callback returns becomes the accumulator for the next item. When there are no items left, reduce returns the final accumulator.

The index and array arguments work the same as they do in filter and map, and you'll rarely need them.

Adding Up Numbers

The classic example is a sum:

const numbers = [1, 2, 3, 4]
const sum = numbers.reduce((total, number) => total + number, 0)
console.log(sum) // 10

Step by step, this is what happens:

  • total starts at 0, plus 1 is 1
  • 1 plus 2 is 3
  • 3 plus 3 is 6
  • 6 plus 4 is 10

Getting a Cart Total

The same idea works for an array of objects. Multiply each item's price by its quantity and add it to the total:

const cart = [
{ name: "T-shirt", price: 20, quantity: 2 },
{ name: "Hat", price: 15, quantity: 1 },
{ name: "Socks", price: 5, quantity: 3 },
]
const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
console.log(total) // 70

If you only want to total some of the items, you can filter the array first and chain reduce after it.

Grouping Items into an Object

The accumulator doesn't have to be a number. Starting with an empty object lets you group items by a key:

const people = [
{ name: "Jim", department: "Sales" },
{ name: "Pam", department: "Reception" },
{ name: "Dwight", department: "Sales" },
]
const byDepartment = people.reduce((groups, person) => {
const key = person.department
if (!groups[key]) {
groups[key] = []
}
groups[key].push(person)
return groups
}, {})
// {
// Sales: [{ name: "Jim", ... }, { name: "Dwight", ... }],
// Reception: [{ name: "Pam", ... }],
// }

Each person gets added to the array for their department, and the array is created the first time a department shows up. Don't forget to return the accumulator, otherwise the next item gets undefined.

Counting Occurrences

A similar trick counts how many times each value shows up:

const votes = ["yes", "no", "yes", "yes", "no"]
const counts = votes.reduce((tally, vote) => {
tally[vote] = (tally[vote] || 0) + 1
return tally
}, {})
console.log(counts) // { yes: 3, no: 2 }

The first time a vote shows up tally[vote] is undefined, so || 0 starts it at zero before adding one.

Flattening an Array

With an empty array as the initial value, reduce can flatten nested arrays:

const nested = [[1, 2], [3, 4], [5]]
const flat = nested.reduce((all, arr) => all.concat(arr), [])
console.log(flat) // [1, 2, 3, 4, 5]

For this one specifically, nested.flat() does the same thing, but it's a good example of how flexible the accumulator is.

Always Pass an Initial Value

The initial value is optional. If you leave it out, reduce uses the first item as the accumulator and starts at the second item. That can cause a couple of surprises:

const empty = []
empty.reduce((total, number) => total + number)
// TypeError: Reduce of empty array with no initial value
const cart = [{ price: 20 }, { price: 15 }]
cart.reduce((total, item) => total + item.price)
// "[object Object]15"

An empty array throws an error, and with objects the accumulator starts as the first object instead of a number. Passing 0 (or {} or []) as the initial value avoids both problems, so it's a good habit to always include it.

Have some feedback on this post? .