You need to enable JavaScript to run this app. JS 如何使用reduce统计同名作业的难度与趣味评分总和
优惠活动
大模型
产品
解决方案
定价
更多

JS 如何使用reduce统计同名作业的难度与趣味评分总和

两类汇总需求的JS实现方案

合并双评分的单条汇总结果

不需要用到嵌套reduce,针对单层数组结构的单轮reduce即可完成统计:

const assignmentsTotal = assignments.reduce((acc, currentItem) => {
  // 匹配累加器内是否已存在同名作业的汇总条目
  const existedRecord = acc.find(record => record.name === currentItem.name)
  if (!existedRecord) {
    // 首次出现的作业直接写入初始汇总值
    acc.push({
      name: currentItem.name,
      totalDifficultyRating: currentItem.difficultyRating,
      totalFunRating: currentItem.funRating
    })
  } else {
    // 已存在的条目直接累加两类评分值
    existedRecord.totalDifficultyRating += currentItem.difficultyRating
    existedRecord.totalFunRating += currentItem.funRating
  }
  return acc
}, [])

拆分独立的两类评分汇总结果

不需要先map拆分数组再两次reduce遍历,同样可以在单轮循环中同时维护两个汇总数组,减少重复遍历开销:

const { difficultyTotal, funTotal } = assignments.reduce((acc, currentItem) => {
  // 分别匹配两个累加数组内的同名作业
  const existedDifficulty = acc.difficultyTotal.find(record => record.name === currentItem.name)
  const existedFun = acc.funTotal.find(record => record.name === currentItem.name)

  if (!existedDifficulty) {
    acc.difficultyTotal.push({
      name: currentItem.name,
      totalDifficultyRating: currentItem.difficultyRating
    })
  } else {
    existedDifficulty.totalDifficultyRating += currentItem.difficultyRating
  }

  if (!existedFun) {
    acc.funTotal.push({
      name: currentItem.name,
      totalFunRating: currentItem.funRating
    })
  } else {
    existedFun.totalFunRating += currentItem.funRating
  }

  return acc
}, { difficultyTotal: [], funTotal: [] })

// 按需求格式赋值
const assignmentsDifficultyTotal = difficultyTotal
const assignmentsFunTotal = funTotal

方案优劣对比

  • 先map拆分独立数组再分别reduce的方案:代码直观但需要对原数组执行至少3次遍历(1次map拆分、2次reduce求和),还会生成两个拆分用的临时数组,存在不必要的性能和内存开销。
  • 单轮reduce实现的方案:仅对原数组执行1次遍历,无多余临时数组生成,在数据量较大的场景下性能优势明显,且逻辑不需要复杂的嵌套结构。

进阶优化:如果原数组条目数较多(超过100条),可以将累加器结构从数组替换为以作业名为键的对象,把原本O(n)的find查找替换为O(1)的对象键值读取,最后在reduce结束后通过Object.values()将对象转换为要求的数组格式,进一步降低时间复杂度。

内容的提问来源于stack exchange,提问作者ZeeAars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.14 12:06:04