Codectionary / Developer documentation / JavaScript

reduce() and reduceRight()

reduce() executes a reducer function on each element, accumulating a single result value - useful for sums, grouping, flattening, or building up any kind of aggregate. It takes an accumulator and the current value, along with an optional initial value for the accumulator. reduceRight() does the same but processes elements from right to left.

Syntax

arr.reduce((accumulator, current) => newAccumulator, initialValue)

Examples

Summing Values

The classic reduce() example - accumulating a total.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 15

// Without an initial value, the first element becomes the starting accumulator
const sumNoInitial = numbers.reduce((total, n) => total + n);
console.log(sumNoInitial); // 15 - same result here, but riskier on empty arrays

Grouping Data

Using reduce() to transform an array into a grouped object.

const people = [
  { name: "Alice", dept: "Engineering" },
  { name: "Bob", dept: "Sales" },
  { name: "Charlie", dept: "Engineering" }
];

const byDept = people.reduce((groups, person) => {
  const key = person.dept;
  if (!groups[key]) groups[key] = [];
  groups[key].push(person.name);
  return groups;
}, {});

console.log(byDept);
// { Engineering: ["Alice", "Charlie"], Sales: ["Bob"] }

Counting Occurrences

Another common reduce() pattern - tallying values.

const votes = ["yes", "no", "yes", "yes", "no"];

const tally = votes.reduce((counts, vote) => {
  counts[vote] = (counts[vote] || 0) + 1;
  return counts;
}, {});

console.log(tally); // { yes: 3, no: 2 }

Best practices

  • Always provide an initial value as the second argument - it avoids errors on empty arrays and makes the starting state explicit
  • Remember to return the accumulator from the callback every time - forgetting this is the single most common reduce() bug
  • Use reduce() for genuinely aggregate operations (sums, grouping, flattening) - for simple transformations, map()/filter() are usually clearer
  • Consider breaking a very complex reduce() into a named function passed as the callback, for readability

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation