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

如何提取数组对象中相同属性项并累加对应sold字段的数值

针对指定条件的累加实现(匹配matri=1且year=2020)

先通过filter方法筛选符合条件的所有条目,再用reduce方法累加所有匹配条目的sold字段值即可,代码示例:

const sold = [
  { matri: 1, year: 2019, sold: 5 },
  { matri: 2, year: 2020, sold: 3 },
  { matri: 1, year: 2020, sold: 7 },
];

// 筛选符合条件的条目
const matchedList = sold.filter(item => item.matri === 1 && item.year === 2020);
// 累加sold字段值
const sumSold = matchedList.reduce((total, current) => total + current.sold, 0);

console.log(sumSold) // 输出结果:12

通用多属性分组累加实现

如果需要批量处理所有matri和year的相同组合,无需逐个指定筛选条件,可以直接用reduce做分组统计,代码示例:

const sold = [
  { matri: 1, year: 2019, sold: 5 },
  { matri: 2, year: 2020, sold: 3 },
  { matri: 1, year: 2020, sold: 7 },
];

// 以matri+year作为分组唯一标识
const groupResult = sold.reduce((acc, item) => {
  const groupKey = `${item.matri}-${item.year}`;
  if (!acc[groupKey]) {
    acc[groupKey] = { ...item, sold: 0 };
  }
  acc[groupKey].sold += item.sold;
  return acc;
}, {});

// 转换为数组格式输出
const finalResult = Object.values(groupResult);
console.log(finalResult)
/* 输出结果:
[
  { matri: 1, year: 2019, sold: 5 },
  { matri: 2, year: 2020, sold: 3 },
  { matri: 1, year: 2020, sold: 12 }
]
*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:45:01