Course contentsShow
← JavaScript
Lesson 864 of 2,72320. Array Iteration and TransformationFree lesson

Building Objects with Reduce

Transform an array into an object by using reduce to accumulate key-value pairs from array elements.

Building Objects with Reduce

You'll learn how to transform an array into an object by accumulating key-value pairs using reduce.

The Core Idea

While reduce is often used for summing numbers, one of its most powerful applications is building objects from arrays. Instead of accumulating a number or array, you can accumulate an object, adding properties to it as you iterate through array elements.

Think of it like this: imagine you're organizing a pile of business cards into a contact book. Each card (array element) provides information you want to add as a new entry (key-value pair) in your book (the accumulator object).

How It Works

The pattern is simple:

  1. Start with an empty object as your initial value: {}
  2. For each element, add or modify a property on the accumulator
  3. Always return the accumulator so it carries forward to the next iteration
const fruits = ['apple', 'banana', 'cherry'];

const fruitLengths = fruits.reduce((acc, fruit) => {
  acc[fruit] = fruit.length;
  return acc;
}, {}); // Start with empty object

// Result: { apple: 5, banana: 6, cherry: 6 }

Here, we're transforming an array of strings into an object where each fruit name becomes a key, and its length becomes the value.

Another Example: Grouping Data

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

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

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

Key Takeaway: Use reduce with an object as the initial value to transform arrays into objects, where each iteration adds or updates properties based on array elements.