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

JavaScript中多对象数组按name求交集并累加count值的实现方法

实现方案

思路

  • 将三个数组合并为一个总数组,统一遍历统计
  • 借助对象做临时哈希映射,以name为键存储累计的count值,时间复杂度为O(n),效率更高
  • 最后将哈希映射转换为目标结构的数组即可

可运行代码

// 已修正原示例中对象的语法错误(将=替换为标准键值对冒号,补充数组项分隔逗号)
const list1 = [
  { name: 'Mark', count: '3' },
  { name: 'Harry', count: '2' }
]
const list2 = [
  { name: 'John', count: '3' },
  { name: 'Mark', count: '1' }
]
const list3 = [
  { name: 'John', count: '3' },
  { name: 'Harry', count: '1' }
]

// 1. 合并所有待统计数组
const totalList = [...list1, ...list2, ...list3]
// 2. 按name统计count总和
const countMap = {}
totalList.forEach(item => {
  const currentName = item.name
  // 将字符串格式的count转为数字累加,避免字符串拼接错误
  const currentCount = Number(item.count)
  countMap[currentName] = (countMap[currentName] || 0) + currentCount
})
// 3. 转换为要求的结果格式
const listResult = Object.entries(countMap).map(([name, totalCount]) => ({
  name,
  count: String(totalCount) // 如果要求count为数字类型,直接写count: totalCount即可
}))

console.log(listResult)

运行输出

[
  { name: 'Mark', count: '4' },
  { name: 'Harry', count: '3' },
  { name: 'John', count: '6' }
]

如果后续需要新增更多统计数组,只需要在totalList的合并逻辑中添加对应数组即可,不需要修改后续统计逻辑,扩展性更好。


内容的提问来源于stack exchange,提问作者ro.nin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 10:45:04