← 中文资源

简体中文版本

数组方法链数据变换

filter/map/flatMap/reduce 组成可读的数据管道:日常列表处理不再手写循环,some/find 做判断查找。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

eu total: 60
prices: [ 10, 20, 5, 30 ]
has na order: true
first big order: 1

实现说明

顶层就这几处状态:orders、euTotal、allPrices。

使用要点

  • 演示输出是带标签的(eu total:、prices:、has na order:),每个操作都会留下自己的一行标注。

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件用顶层绑定保存自己的状态:orders、euTotal、allPrices。

核心语句

.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));

代码示例

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);