You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS如何使用reduce方法对对象数组求和并统计重复项

代码问题分析

  • 你在累加逻辑里写了['marks'].forEach(...),但你的水果对象根本不存在marks属性,读取不到的属性值为undefined,和数字相加后结果自然是NaN,你实际要累加的应该是amount字段。
  • 没有新增count字段的相关逻辑,既没有在初始化分组对象时设置count的初始值,也没有在命中同类型分组时累加count数值。

正确实现代码

const fruits = [{
    type: "oranges",
    amount: 10
  },
  {
    type: "apples",
    amount: 0,
  }, {
    type: "oranges",
    amount: 5
  }
]

const endresult = Object.values(fruits.reduce((acc, cur) => {
  if (acc[cur.type]) {
    // 同类型已存在,累加数量、计数+1
    acc[cur.type].amount += cur.amount
    acc[cur.type].count += 1
  } else {
    // 同类型不存在,初始化分组,计数默认设为1
    acc[cur.type] = {...cur, count: 1}
  }
  return acc
}, {}))

console.log(endresult)

运行后输出的结果和你预期的格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:06:01