Course contentsShow
← JavaScript
Lesson 458 of 2,72312. Higher-Order FunctionsFree lesson

Building Objects with Reduce

Accumulating into an object to count occurrences, group items, or create lookup tables.

Building Objects with Reduce

You'll learn how to use reduce to transform arrays into objects for counting, grouping, and creating lookup tables.

Why Build Objects with Reduce?

While reduce is great for summing numbers, its real power shines when accumulating into an object. This lets you transform array data into structured, easy-to-query objects.

Core Patterns

Counting Occurrences

Think of taking attendance: you start with an empty roster (object) and add a tally mark each time you see a name.

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

// Result: { apple: 3, banana: 2, orange: 1 }

Grouping Items

Like sorting mail into boxes by address:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Carol', age: 25 }
];

const byAge = people.reduce((acc, person) => {
  if (!acc[person.age]) {
    acc[person.age] = [];
  }
  acc[person.age].push(person);
  return acc;
}, {});

// Result: { 25: [{Alice}, {Carol}], 30: [{Bob}] }

Creating Lookup Tables

Transform an array into instant-access storage:

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

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

// Result: { 1: {id: 1, name: 'Alice'}, 2: {id: 2, name: 'Bob'} }

The Pattern

Start with an empty object {}, check if a key exists, create or update it, and always return the accumulator.

Key Takeaway: Reduce transforms arrays into objects by accumulating key-value pairs, perfect for counting, grouping, or creating fast-lookup data structures.