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

Combining Map and Filter

Chaining filter and map together to first select elements, then transform them.

Combining Map and Filter

You'll learn how to chain filter and map together to create powerful data transformations in just two steps.

The Core Idea

When working with arrays, you often need to do two things: first, select only certain elements (filtering), and then transform those selected elements (mapping). Instead of creating intermediate variables or using separate loops, you can chain these methods together in one elegant expression.

The pattern is simple: filter first, then map. Filtering reduces your array to only the items you care about, and mapping transforms those survivors into the shape you need.

How It Works

When you chain filter and map, JavaScript:

  1. Runs filter on the original array, producing a new array with fewer items
  2. Immediately runs map on that filtered result, transforming each remaining item
  3. Returns the final transformed array
const numbers = [1, 2, 3, 4, 5, 6];

// Get the squares of only even numbers
const evenSquares = numbers
  .filter(num => num % 2 === 0)  // [2, 4, 6]
  .map(num => num * num);         // [4, 16, 36]

console.log(evenSquares);  // [4, 16, 36]

Think of It Like an Assembly Line

Imagine packages on a conveyor belt. The filter station removes any packages that don't meet quality standards. The map station then repackages everything that made it through. Only the items that pass the first checkpoint get transformed at the second.

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

const adultNames = users
  .filter(user => user.age >= 18)
  .map(user => user.name);

console.log(adultNames);  // ['Alice', 'Carol']

Key Takeaway: Chain filter before map to first select the elements you want, then transform only those elements—creating clean, readable data pipelines without intermediate variables.