Array Method Chaining Data Transforms
Compose filter, map, flat, and reduce into readable data pipelines that replace hand-rolled loops for everyday list processing.
Code
const orders = [
{ id: 1, region: 'eu', items: [{ price: 10 }, { price: 20 }] },
{ id: 2, region: 'na', items: [{ price: 5 }] },
{ id: 3, region: 'eu', items: [{ price: 30 }] },
];
// filter → map → reduce:日常列表处理三板斧
const euTotal = orders
.filter((o) => o.region === 'eu')
.reduce((sum, o) => sum + o.items.reduce((s, i) => s + i.price, 0), 0);
console.log('eu total:', euTotal);
// flatMap:一层展开(拍平子列表)
const allPrices = orders.flatMap((o) => o.items.map((i) => i.price));
console.log('prices:', allPrices);
// 查找与判断
console.log('has na order:', orders.some((o) => o.region === 'na'));
console.log('first big order:', orders.find((o) => o.items.length > 1)?.id);Output
Captured from a sandboxed run of this snippet in the build pipeline.
eu total: 60
prices: [ 10, 20, 5, 30 ]
has na order: true
first big order: 1How it works
Module-level bindings hold the data — orders, euTotal, allPrices — with no function scope in between.
Putting it to use
Running the file prints labeled results such as eu total:, prices:, has na order: — each operation’s effect is visible in the output.
Core lines
.reduce((sum, o) => sum + o.items.reduce((s, i) => s + i.price, 0), 0);
const allPrices = orders.flatMap((o) => o.items.map((i) => i.price));
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `orders`, `euTotal`, `allPrices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.