JavaScript reduce() Explained: Totals, Grouping, and Accumulators

Learn how JavaScript reduce() combines array values, calculate a portfolio total, group records, and choose a safe initial value.

JavaScript reduce() Explained: Totals, Grouping, and Accumulators

What is reduce() Used For?

Suppose an investment dashboard shows several holdings, and you need one number for their combined value. Or you have a list of products and want to group them by category. JavaScript's reduce() can build that result by processing an array one item at a time.

reduce() is an array method that runs a callback for each element and carries a value forward, called the accumulator. The accumulator can be a number, object, array, or string. It is a flexible tool, but it is not automatically the clearest choice for every array task. Use map() when you want to transform every item, and filter() when you want matching items.

The basic shape

const result = array.reduce((accumulator, currentValue) => {
  // Update or replace the accumulator
  return accumulator;
}, initialValue);

The callback receives the accumulator first and the current array element second. You can also receive the current index and the original array as its third and fourth arguments. The value returned by the callback becomes the accumulator for the next item. After the last item, reduce() returns the final accumulator.

The second argument to reduce() is the initial value. It gives the accumulator a known starting value and determines its type. For beginner code, it is usually best to provide one.

Add up an investment portfolio

Imagine each holding records how many shares you own and the current price per share. The value of one holding is quantity * price:

const holdings = [
  { symbol: "ABC", quantity: 3, price: 100 },
  { symbol: "XYZ", quantity: 2, price: 250 },
  { symbol: "LMN", quantity: 5, price: 40 },
];

const portfolioValue = holdings.reduce((total, holding) => {
  return total + holding.quantity * holding.price;
}, 0);

console.log(portfolioValue); // 1000

The 0 is the starting total. On the first pass, total is 0 and the first holding contributes 3 * 100, so the callback returns 300. Next, it adds 2 * 250 and returns 800. Finally, it adds 5 * 40 and returns 1000.

PassHolding valueAccumulator after the pass
Start—0
13 × 100 = 300300
22 × 250 = 500800
35 × 40 = 2001000

In a real finance application, this simple total assumes prices are already in the same currency and use an appropriate representation. Rounding and currency conversion are separate concerns.

Group items into an object

The accumulator does not have to be a number. Here, start with an empty object and collect each product into an array under its category:

const products = [
  { name: "Notebook", category: "stationery" },
  { name: "Pen", category: "stationery" },
  { name: "Mug", category: "kitchen" },
];

const productsByCategory = products.reduce((groups, product) => {
  const category = product.category;

  if (!groups[category]) {
    groups[category] = [];
  }

  groups[category].push(product);
  return groups;
}, {});

console.log(productsByCategory);
// {
//   stationery: [{ name: "Notebook", ... }, { name: "Pen", ... }],
//   kitchen: [{ name: "Mug", ... }]
// }

The accumulator groups is the object created by {}. Each pass ensures the current category has an array, adds the product, and returns the same accumulator object for the next pass.

Why pass an initial value?

With an initial value of 0, reducing an empty array returns 0, and the callback is not called:

const total = [].reduce((sum, number) => sum + number, 0);
console.log(total); // 0

If you omit the initial value, reduce() uses the first element as the initial accumulator and starts the callback at the second element. An empty array without an initial value throws a TypeError. The chosen type matters too: a numeric sum should start with 0, while grouping should start with {}.

Common mistakes

  • Forgetting to return the accumulator. Without return, the next callback receives undefined.
  • Starting with the wrong value. Start a sum with 0, a grouped result with {}, or a collected list with [].
  • Using reduce() for every array operation. A short map(), filter(), or forEach() may communicate your intent better.
  • Forgetting empty arrays. Supplying an initial value gives empty input a predictable result.

Try it yourself

Given this array, use reduce() to calculate the total number of books. Then change the initial value and callback to create an object that groups the books by genre.

const books = [
  { title: "River", genre: "fiction", copies: 4 },
  { title: "Stars", genre: "science", copies: 2 },
  { title: "Garden", genre: "fiction", copies: 3 },
];

For the total, add each book's copies to a numeric accumulator. For grouping, use an object accumulator and put each book into the array for its genre.

Recap

  • reduce() processes array elements and returns the final accumulator.
  • The callback receives the accumulator and the current element.
  • The accumulator can be a number, object, array, or another value.
  • Pass an initial value to define the starting type and handle empty arrays safely.
  • Prefer a simpler array method when it makes your intent clearer.

What's next?

Next, learn how some() and every() check whether some or all array elements satisfy a condition.

Written by

Dev Likhon

Dev Likhon

Full Stack Developer & Tech Educator

6+ years of professional development experience.

About Me
Share:

Comments

Share what you learned or ask a question.

Loading comments...