AZ.dev

Array reduce: sum values and transform objects

| node: 12+ browsers: all modern

Array.reduce() iterates an array and accumulates a single result. The key: always return the accumulator.

Sum numbers

const total = [10, 20, 30].reduce((sum, n) => sum + n, 0);
// 60

Transform an array into an object

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

const byId = users.reduce((map, user) => {
  map[user.id] = user;
  return map;
}, {});

// { 1: { id: 1, name: "Alice" }, 2: { id: 2, name: "Bob" } }

Group items by a key

const items = [
  { type: "fruit", name: "apple" },
  { type: "veg", name: "carrot" },
  { type: "fruit", name: "banana" },
];

const grouped = items.reduce((groups, item) => {
  const key = item.type;
  groups[key] = groups[key] || [];
  groups[key].push(item);
  return groups;
}, {});

When NOT to use reduce

Use map when input and output arrays have the same length. Use filter when selecting a subset. Use Object.groupBy() (ES2024) instead of the grouping pattern above:

// Modern alternative (Node 21+, Chrome 117+)
const grouped = Object.groupBy(items, (item) => item.type);

Gotchas

arrays reduce functional transform

Was this helpful?