reduce是JS数组最强大的遍历方法,可实现累计、分组、嵌套扁平化、多条件统计等;初始化累加器后在回调中更新,返回单值(数字/对象/数组/Promise)。

reduce 是 JS 数组中功能最强大的遍历方法之一,特别适合做累计、分组、嵌套结构扁平化、多条件统计等复杂计算。它不直接返回新数组,而是把整个数组“压缩”成一个值——这个值可以是数字、对象、数组,甚至 Promise。
用 reduce 做基础累计统计(求和、计数、平均值)
核心在于正确初始化 accumulator(累加器),并在每次迭代中更新它。
- 求和:初始值设为
0,每次加当前项 - 计数(如统计正数个数):初始值为
0,满足条件才 +1 - 平均值:先用 reduce 算出总和与数量,最后相除(注意避免空数组除零)
示例:
const nums = [2, 4, 6, 8];const sum = nums.reduce((acc, cur) => acc + cur, 0); // 20
const positiveCount = nums.reduce((acc, cur) => cur > 5 ? acc + 1 : acc, 0); // 2
用 reduce 实现分组统计(按字段聚合)
把累加器初始化为一个空对象 {},以分类 key 为属性名,值为对应子集或统计结果。
- 按类型分组商品:
acc[type] = acc[type] || [],再 push - 按城市统计订单总额:
acc[city] = (acc[city] || 0) + order.amount - 同时统计数量和金额:
acc[city] = { count: ..., total: ... },需手动初始化对象
示例(统计各状态订单数):
const byStatus = orders.reduce((acc, order) => {
acc[order.status] = (acc[order.status] || 0) + 1;
return acc;
}, {}); // { paid: 2, pending: 1 }
用 reduce 处理嵌套结构(扁平化+统计)
当数据含数组字段(如用户有多个标签、订单含多个商品),可在 reduce 中嵌套一次 map/flat/reduce,把深层数据提上来再统计。
- 统计所有用户的全部标签出现频次:先用
flatMap提取所有 tag,再 reduce 计数 - 计算多级费用总和:对每个 item 的
subItems调用 reduce 求和,再累加到顶层 - 避免重复遍历:不要在 reduce 外先 flat,而是在回调里动态展开,节省内存
示例(统计所有评论的点赞总数):
const posts = [{ title: 'A', comments: [{ likes: 5 }, { likes: 2 }] },
{ title: 'B', comments: [{ likes: 3 }] }
];
const totalLikes = posts.reduce((sum, post) =>
sum + post.comments.reduce((s, c) => s + c.likes, 0),
0
); // 10
用 reduce 做条件过滤+转换+统计一体化
reduce 不必只做“加法”,它可以替代 filter + map + reduce 三连操作,在单次遍历中完成逻辑判断、数据提取和聚合,性能更好、逻辑更集中。
- 只统计近 7 天且已完成的订单金额:在回调中先判断
if (isRecent && isDone),再累加 - 构建带索引的映射表(如 id → {item, index}):累加器为对象,每次存
acc[item.id] = { ...item, index } - 找最大值/最小值/首次匹配项:初始值设为
null或undefined,用比较逻辑更新
示例(找价格最高的商品并记录位置):
const items = [{name: 'a', price: 100}, {name: 'b', price: 150}, {name: 'c', price: 90}];const maxItem = items.reduce((max, cur, i) =>
max === null || cur.price > max.price ? { ...cur, index: i } : max,
null
); // { name: 'b', price: 150, index: 1 }


















