Sub topic 14
Building Data Pipelines by Chaining Methods
This chapter assumes you already know map, filter, reduce, the search methods such as find and some, and the difference between sort and toSorted. You should also be comfortable with arrow functions and template literals. Here you will combine those methods into pipelines, decide what order the steps should run in, debug a chain that gives the wrong result, and recognize when a chain is the wrong tool.
Why Chaining Works
Chaining works because many array methods return a new array. That return value has all the array methods, so you can call the next method directly on it:
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); // 65Each line is one step with one job. filter returns a two-element array of order objects. map turns that into [40, 25]. reduce collapses it to 65. The original orders array is never modified.
The rule to keep in mind: a method can only be chained onto the step before it if that step returns an array. You can sort array methods into three groups by what they return:
| Role in a chain | Methods | Returns |
|---|---|---|
| Middle step (array in, array out) | `filter`, `map`, `flatMap`, `slice`, `concat`, `toSorted`, `toReversed`, `toSpliced`, `with`, `flat` | A new array |
| Final step (array in, one value out) | `reduce`, `find`, `findIndex`, `some`, `every`, `includes`, `join` | A single value |
| Avoid in a chain | `forEach`, `push`, `sort`, `reverse`, `splice` | `undefined`, a length, or the mutated original |
sort and reverse do return an array, so the chain keeps running. The problem is that they mutate the array they are called on. That is usually harmless when they come after a filter, because filter already made a fresh array. When they are the first step, they mutate your source data. Use toSorted and toReversed so the chain is safe wherever you put the step.
A Realistic Pipeline
This pipeline builds a short "top picks" label from a product list. It uses filtering, sorting, truncating, formatting, and joining:
const products = [
{ name: 'Desk', price: 180, stock: 4, category: 'office' },
{ name: 'Lamp', price: 35, stock: 0, category: 'office' },
{ name: 'Chair', price: 120, stock: 7, category: 'office' },
{ name: 'Mug', price: 12, stock: 30, category: 'kitchen' },
{ name: 'Shelf', price: 90, stock: 2, category: 'office' }
];
const topOffice = products
.filter(p => p.category === 'office')
.filter(p => p.stock > 0)
.toSorted((a, b) => b.price - a.price)
.slice(0, 2)
.map(p => `${p.name} ($${p.price})`)
.join(', ');
console.log(topOffice); // 'Desk ($180), Chair ($120)'
console.log(products[0].name); // 'Desk' (source order unchanged)Put each method on its own line, starting with the dot. This layout lets you read the steps top to bottom, comment out a single step, and see each change on its own line in version control diffs.
You could merge the two filter calls into one with &&. Keeping them separate costs one extra pass but makes each rule easy to read and remove. Either choice is fine. Pick the one that reads better for the condition at hand.
Order of Steps Matters
The order of steps affects correctness and the amount of work done.
Filter early. Every later step runs on fewer elements. If map does something expensive, such as formatting dates or parsing strings, run it after filter, not before.
Keep the data you need for later steps. Once map replaces objects with numbers, later steps can no longer see the other fields:
const items = [
{ name: 'A', price: 10, active: true },
{ name: 'B', price: 50, active: false }
];
// Wrong: after map, there is no .active to filter on
const broken = items
.map(i => i.price)
.filter(i => i.active);
console.log(broken); // []
// Right: filter while the objects are still intact
const fixed = items
.filter(i => i.active)
.map(i => i.price);
console.log(fixed); // [10]Sort before slicing when you want the "top N". If you slice(0, 3) and then sort, you get the first three items in sorted order, not the three largest.
Ending a Chain
A chain usually ends with a step that turns the array into what the caller needs. reduce is the most flexible final step. This one groups the in-stock office products by price band:
const products = [
{ name: 'Desk', price: 180, stock: 4 },
{ name: 'Chair', price: 120, stock: 7 },
{ name: 'Shelf', price: 90, stock: 2 },
{ name: 'Lamp', price: 35, stock: 0 }
];
const byBand = products
.filter(p => p.stock > 0)
.reduce((groups, p) => {
const band = p.price >= 100 ? 'premium' : 'standard';
(groups[band] ??= []).push(p.name);
return groups;
}, {});
console.log(byBand); // { premium: ['Desk', 'Chair'], standard: ['Shelf'] }Calling push here is fine. It mutates the accumulator, which this reduce created from {}, and never touches the source array. Newer runtimes (ES2024, Node 21+) also provide Object.groupBy(array, fn) for this exact pattern.
Debugging a Chain
When a chain returns the wrong result, find the step where the data first goes wrong. There are two quick techniques.
The first is to split the chain into named variables temporarily and log each one:
const data = [3, 8, 1, 12, 5];
const big = data.filter(n => n > 4);
console.log('after filter:', big); // [8, 12, 5]
const doubled = big.map(n => n * 2);
console.log('after map:', doubled); // [16, 24, 10]
const total = doubled.reduce((s, n) => s + n, 0);
console.log(total); // 50The second is to insert a logging step that passes the array through unchanged. A small helper keeps the chain intact:
const peek = label => (x, i, arr) => {
if (i === 0) console.log(label, arr);
return x;
};
const result = [3, 8, 1, 12, 5]
.filter(n => n > 4)
.map(peek('after filter:')) // logs [8, 12, 5] once
.map(n => n * 2)
.reduce((s, n) => s + n, 0);
console.log(result); // 50peek uses the third callback argument, arr, to log the whole input array once. If the input is empty, the callback never runs and nothing is logged. An empty input is itself a useful clue.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Array of `undefined` values | Arrow function with braces and no `return`: `x => { x * 2 }` | Use `x => x * 2` or add `return` |
| `TypeError: Cannot read properties of undefined` | `forEach` returned `undefined` and the next method was called on it | Use `map` if you need a result, or end the chain with `forEach` |
| Source array is reordered | `sort` or `reverse` was the first step | Use `toSorted` or `toReversed` |
| `TypeError` when calling a method on the result of `find` | `find` returns one element (or `undefined`), not an array | Use `filter` if you need an array, or check the result before using it |
| `TypeError: Reduce of empty array with no initial value` | A filter step removed every element | Pass an initial value to `reduce` |
When Not to Chain
Each middle step walks over the whole array and allocates a new one. For a few thousand elements this costs almost nothing, and the readability is worth it. Rewrite the chain as a single loop or one reduce when:
- The array is very large (hundreds of thousands of elements or more) and profiling shows the pipeline is a hot path.
- You need to stop early. A chain cannot break out of
map. Afor...ofloop withbreak, or a finalfindorsome, can. - A step needs state from earlier steps that does not fit cleanly into the data flowing through the chain.
// Single pass: sum the doubled values of numbers over 4
let total = 0;
for (const n of [3, 8, 1, 12, 5]) {
if (n > 4) total += n * 2;
}
console.log(total); // 50Start with the chain. Switch to a loop when you have a measured reason.
Exercise
Given const scores = [{ player: 'Ana', points: 72 }, { player: 'Ben', points: 45 }, { player: 'Cleo', points: 91 }, { player: 'Dev', points: 60 }];, write one chain that returns the names of players with 60 or more points, highest score first, as a single string like 'Cleo, Ana, Dev'. The scores array must not be reordered.
Show answer
scores.filter(s => s.points >= 60).toSorted((a, b) => b.points - a.points).map(s => s.player).join(', ') returns 'Cleo, Ana, Dev'. Filtering first keeps the objects intact for sorting. toSorted leaves the original order alone, and map runs last because sorting still needs the points field.
Exercise
This code logs an array of undefined values: const labels = items.filter(i => i.ok).map(i => { \#${i.id}\ });. Why, and how do you fix it?
Show answer
With braces, an arrow function body is a block, so the template literal is evaluated and thrown away and the callback returns undefined. Remove the braces, map(i => \#${i.id}\), or write map(i => { return \#${i.id}\; }).
Exercise
A teammate writes const firstBig = nums.filter(n => n > 100)[0]; on an array with a million elements. What is a better choice, and why?
Show answer
Use nums.find(n => n > 100). filter checks every element and builds a whole new array just to read its first item. find stops at the first match and allocates nothing. Both return undefined if no element matches.