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

Chaining Transformations: When Reduce Replaces Map/Filter

Learn when reduce can replace multiple chained array methods for better performance with a single pass.

Chaining Transformations: When Reduce Replaces Map/Filter

You'll learn when a single reduce can efficiently replace multiple chained array methods like map and filter.

The Performance Problem with Chaining

When you chain map and filter, JavaScript creates intermediate arrays at each step. Each method makes a complete pass through the array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Two passes through the array
const result = numbers
  .filter(n => n % 2 === 0)  // Pass 1: creates [2, 4, 6, 8, 10]
  .map(n => n * n);          // Pass 2: creates [4, 16, 36, 64, 100]

console.log(result); // [4, 16, 36, 64, 100]

This works fine but creates temporary arrays and loops through data multiple times.

Using Reduce for a Single Pass

You can combine both operations into one reduce call that processes each element only once:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Single pass through the array
const result = numbers.reduce((acc, n) => {
  if (n % 2 === 0) {        // Filter logic
    acc.push(n * n);        // Map logic
  }
  return acc;
}, []);

console.log(result); // [4, 16, 36, 64, 100]

When to Use Each Approach

  • Use chained map/filter: For clarity and readability in most cases
  • Use reduce: When working with large datasets where performance matters, or when the transformation logic is naturally combined

Think of it like cooking: chaining is like washing vegetables, then chopping them separately. Reduce is like washing and chopping each vegetable before moving to the next—fewer steps, one bowl.

Key Takeaway: While map and filter chains are more readable, reduce can replace them with a single pass through the array, improving performance for large datasets by avoiding intermediate arrays.