Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript reduce()

reduce turns an array into a single value like a sum, object, or combined list.

It is powerful but should be used with care for readability.

Why We Need It

Many tasks require aggregating data. reduce handles those in one pass.

It is a key tool for data transformation pipelines.

Syntax

array.reduce((acc, value, index, array) => newAcc, initialValue)

Basic Example

1. Sum numbers

const nums = [1, 2, 3];
const total = nums.reduce((sum, n) => sum + n, 0);

console.log(total);

Accumulate a sum with an initial value.

Real World Example

2. Build an object

const items = ["a", "b"];
const counts = items.reduce((acc, item) => {
  acc[item] = (acc[item] || 0) + 1;
  return acc;
}, {});

console.log(counts);

Use reduce to build objects from arrays.

Multiple Use Cases

Collapse to One Value

reduce combines all elements into a single result.

You control the accumulator and how it updates each step.

Initial Value

Always provide an initial value to avoid edge cases on empty arrays.

The initial value sets the type of your accumulator.

More Than Numbers

reduce can build objects, group data, or flatten arrays.

It is powerful but should stay readable.

More Examples

3. Group by key

const users = [{ role: "admin" }, { role: "user" }];
const grouped = users.reduce((acc, u) => {
  (acc[u.role] ||= []).push(u);
  return acc;
}, {});

console.log(grouped);

Group array items into buckets.

4. Flatten once

const nested = [[1, 2], [3]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);

console.log(flat);

Reduce can flatten one level.

Comparison

Without

let total = 0;
for (const n of nums) {
  total += n;
}

With

const total = nums.reduce((sum, n) => sum + n, 0);

Common Mistakes and Fixes

No initial value

Provide an initial value to avoid surprises on empty arrays.

Overcomplicated reducer

Keep reducer logic readable or split into helpers.

Mutating external state

Work with the accumulator instead of globals.

Interview Questions

What is the accumulator?

The running result that reduce updates each iteration.

Why is initial value important?

It defines the accumulator type and handles empty arrays.

When should you avoid reduce?

When map or filter is clearer.

Practice Problem

Practice: Use reduce to calculate the total price of a cart.

const cart = [10, 15, 5];
// TODO: total price

One Possible Solution

const cart = [10, 15, 5];
const total = cart.reduce((sum, n) => sum + n, 0);
console.log(total);

Frequently Asked Questions

What does reduce return?

A single value produced by the reducer.

Why use an initial value?

It prevents errors and controls accumulator type.

Can reduce replace map and filter?

Yes, but it may reduce readability.

Try It Yourself

Try changing the array to see the accumulator update.