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

Implementing Map and Filter with Reduce

Showing that reduce is powerful enough to express both map and filter operations.

Implementing Map and Filter with Reduce

You'll learn how reduce is powerful enough to recreate both map and filter, proving it's the most fundamental array operation.

The Core Idea

Think of reduce as the Swiss Army knife of array methods. While map and filter are specialized tools, reduce can do their jobs and more. Understanding this reveals the true flexibility of reduce and deepens your grasp of functional programming patterns.

Map with Reduce

When you map, you transform each element and collect results. With reduce, you build that collection manually:

const numbers = [1, 2, 3, 4];

// Traditional map
const doubled = numbers.map(n => n * 2);

// Same result with reduce
const doubledWithReduce = numbers.reduce((acc, n) => {
  acc.push(n * 2);
  return acc;
}, []);

console.log(doubled); // [2, 4, 6, 8]
console.log(doubledWithReduce); // [2, 4, 6, 8]

You start with an empty array ([]) and push transformed values into it.

Filter with Reduce

When you filter, you conditionally include elements. With reduce, you control what gets added:

const numbers = [1, 2, 3, 4];

// Traditional filter
const evens = numbers.filter(n => n % 2 === 0);

// Same result with reduce
const evensWithReduce = numbers.reduce((acc, n) => {
  if (n % 2 === 0) {
    acc.push(n);
  }
  return acc;
}, []);

console.log(evens); // [2, 4]
console.log(evensWithReduce); // [2, 4]

The condition decides whether an element joins the accumulator array.

Why This Matters

This demonstrates that map and filter are actually specialized shortcuts built on reduce's foundation. Whenever you need behavior that combines aspects of both (or goes beyond), reduce is your answer.

Key Takeaway: reduce can implement both map and filter by controlling what gets added to the accumulator, making it the most versatile array method you'll encounter.