Combining map and filter
What you'll learn: How to chain filter and map together to both select and transform array elements in a single expression.
The Power of Chaining
Since both filter and map return new arrays, you can call one method directly on the result of another. This lets you build data transformation pipelines that are clean and readable.
The order matters:
- Filter then map: Remove unwanted elements first, then transform what remains
- Map then filter: Transform everything first, then remove unwanted results
Filter Then Map (Most Common)
This approach is usually more efficient because you transform fewer items:
const numbers = [1, 2, 3, 4, 5, 6];
// Get squares of even numbers only
const evenSquares = numbers
.filter(num => num % 2 === 0) // [2, 4, 6]
.map(num => num * num); // [4, 16, 36]
console.log(evenSquares); // [4, 16, 36]
Map Then Filter
Sometimes you need to transform first, then decide what to keep:
const words = ['hello', 'a', 'world', 'hi'];
// Get uppercase versions, but only if length > 2
const longUppercase = words
.map(word => word.toUpperCase()) // ['HELLO', 'A', 'WORLD', 'HI']
.filter(word => word.length > 2); // ['HELLO', 'WORLD']
console.log(longUppercase); // ['HELLO', 'WORLD']
Think Pipeline
Imagine a factory assembly line: items flow through stations. filter is a quality control checkpoint that removes defects. map is a modification station that changes each item. You arrange these stations in whatever order makes sense for your data.
Key Takeaway: Chain filter and map to create powerful data transformation pipelines—filter then map when you want to transform fewer items, map then filter when the transformation determines what to keep.