Sub topic 14
Building Data Pipelines by Chaining Methods
This chapter assumes you already know map, filter, reduce, and toSorted, and that you can tell mutating methods from non-mutating ones. It shows how to connect those methods into one readable pipeline.
Why Chaining Works
Methods like filter, map, slice, and toSorted return a new array. You can call another array method directly on that result. Each step receives the output of the previous step, so the code reads from top to bottom like a list of instructions.
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 25, paid: true }
];
const paidTotal = orders
.filter(order => order.paid)
.map(order => order.total)
.reduce((sum, total) => sum + total, 0);
console.log(paidTotal); // 65Where the Chain Ends
A chain continues only while each step returns an array. reduce, find, some, every, includes, and join return a single value, so they usually come last. forEach returns undefined, so nothing can follow it.
A Longer Pipeline
The pipeline below finds the names of the two products with the highest revenue:
const sales = [
{ product: 'pen', qty: 10, price: 1.5 },
{ product: 'book', qty: 2, price: 12 },
{ product: 'bag', qty: 0, price: 30 },
{ product: 'mug', qty: 4, price: 8 }
];
const topTwo = sales
.filter(s => s.qty > 0)
.map(s => ({ name: s.product, revenue: s.qty * s.price }))
.toSorted((a, b) => b.revenue - a.revenue)
.slice(0, 2)
.map(s => s.name);
console.log(topTwo); // ['mug', 'book']
console.log(sales.length); // 4 (original untouched)Common Errors
| Mistake | Effect | Fix |
|---|---|---|
| Using `sort` or `reverse` in a chain that starts on the original array | The source array is changed in place | Use `toSorted` or `toReversed`, or call them after a step that already made a copy |
| Calling `map` before `filter` | Work is done on elements you then throw away | Filter first so later steps handle fewer items |
| Leaving out the initial value in `reduce` | Throws a `TypeError` if the filter step returns nothing | Always pass an initial value, such as `0` |
| Putting side effects such as logging or pushing to outer arrays inside `map` | Hard-to-track bugs | Keep callbacks pure and use `forEach` for side effects |
Readability and Debugging
Put each method on its own line with the dot at the start. If a step gets complicated, move its callback into a named function, for example .filter(isPaid). To inspect a step, split the chain into named variables for a moment, or add .map(x => (console.log(x), x)).
Each step loops over the array again. For a few thousand elements the cost doesn't matter. If you measure a real slowdown, merge the steps into a single reduce or a for...of loop.
Exercise
Given const items = [{ name: 'tea', stock: 3 }, { name: 'coffee', stock: 0 }, { name: 'cocoa', stock: 5 }];, write a chain that returns the names of in-stock items in alphabetical order without changing items.
Show answer
items.filter(i => i.stock > 0).map(i => i.name).toSorted() returns ['cocoa', 'tea']. Because map already produces a new array, .sort() would also leave items unchanged, but toSorted makes that intent explicit.
Exercise
Why does orders.filter(o => o.paid).reduce((s, o) => s + o.total) crash when no orders are paid, and how do you fix it?
Show answer
filter returns an empty array, and calling reduce on an empty array without an initial value throws a TypeError. Pass 0 as the second argument: .reduce((s, o) => s + o.total, 0).