Sub topic 8
Building Pipelines by Chaining Methods
This chapter assumes you know how map, filter, and reduce work on their own, including why reduce usually needs an initial value. Here you will combine them into one expression that turns raw data into a final result.
Why Chaining Works
Chaining means calling one method directly on the result of another. It works because map and filter both return a new array, and every array has the same methods. So the output of one step is a valid input for the next.
reduce is different. It returns whatever the accumulator becomes, often a number or an object. Most of the time that means reduce ends the chain.
| Method | Returns | Can you keep chaining array methods? |
|---|---|---|
| `filter` | A new array, the same length or shorter | Yes |
| `map` | A new array of the same length | Yes |
| `reduce` | The final accumulator value | Only if the accumulator is an array |
A Worked Pipeline
Suppose you want the total revenue from paid orders:
const orders = [
{ id: 1, total: 50, status: 'paid' },
{ id: 2, total: 20, status: 'pending' },
{ id: 3, total: 80, status: 'paid' }
];
const paidRevenue = orders
.filter(order => order.status === 'paid')
.map(order => order.total)
.reduce((sum, total) => sum + total, 0);
console.log(paidRevenue); // 130Read it from top to bottom. Each line does one job:
filterkeeps orders 1 and 3.mapturns them into the numbers[50, 80].reduceadds those numbers, starting from0.
The initial value 0 matters here. If no orders were paid, filter would return [], and reduce without an initial value would throw a TypeError. When a pipeline ends in reduce, always pass an initial value, because an earlier filter can empty the array.
Order of Steps Matters
You could write the same pipeline with map first, but then you would lose the status field before you could filter on it. As a rule, filter as early as you can. Then every later step works on fewer elements, and each callback gets the data it needs.
const words = [' Apple', 'kiwi ', ' banana', 'fig'];
const longWordsUpper = words
.map(w => w.trim()) // clean first, so lengths are accurate
.filter(w => w.length > 3) // then drop short words
.map(w => w.toUpperCase()); // then transform what is left
console.log(longWordsUpper); // ['APPLE', 'KIWI', 'BANANA']Here map runs first on purpose. Filtering by length before trimming would count the spaces, and 'kiwi ' would pass for the wrong reason. Put each step where its input has the shape it expects.
Keeping Chains Readable
- Put each method on its own line, with the dot at the start of the line.
- Keep every callback short. If a callback grows past one expression, give it a name.
- Use names that describe what a step does.
const isPaid = order => order.status === 'paid';
const toTotal = order => order.total;
const add = (a, b) => a + b;
const revenue = orders.filter(isPaid).map(toTotal).reduce(add, 0);Exercise
Given const cart = [{ name: 'pen', price: 2, qty: 3, inStock: true }, { name: 'ink', price: 10, qty: 1, inStock: false }, { name: 'pad', price: 5, qty: 2, inStock: true }];, write a chain that returns the total cost of in-stock items only. What value does it produce, and why must reduce have an initial value?
Show answer
cart.filter(item => item.inStock).map(item => item.price * item.qty).reduce((sum, cost) => sum + cost, 0) returns 16 (6 + 10). The initial value 0 keeps the result correct and stops a TypeError if no items are in stock and filter returns an empty array.
Exercise
Why does orders.map(o => o.total).filter(o => o.status === 'paid') return an empty array?
Show answer
After map, each element is a number, so o.status is undefined and the predicate is false for every element. Filter has to run before map discards the status field.