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

JavaScript中如何合并两个高阶函数实现数组对应项属性求和

实现方法

原有代码的问题有三点:

  • 嵌套调用map会遍历两个数组的全部元素组合,生成笛卡尔积结果,无法实现按位置一一匹配元素
  • 直接对item1、item2整个对象做加法,没有读取对象内的具体属性值,会得到无意义的运算结果
  • 外层map的回调函数没有返回值,内层map的执行结果没有被对外返回,最终生成的数组元素全为undefined

两个数组长度一致时,不需要嵌套遍历,直接利用map回调的第二个参数(当前元素索引),匹配第二个数组相同位置的元素,再对同名字段求和即可。

固定属性的实现代码:

const myArr1 = [
  { attr1: 5, attr2: 9, attr3: 3 },
  { attr1: 4, attr2: 1, attr3: 8 },
  { attr1: 1, attr2: 3, attr3: 1 },
]

const myArr2 = [
  { attr1: 7, attr2: 8, attr3: 5 },
  { attr1: 8, attr2: 2, attr3: 1 },
  { attr1: 3, attr2: 9, attr3: 7 },
]

const total = myArr1.map((item1, index) => {
  const item2 = myArr2[index]
  return {
    attr1: item1.attr1 + item2.attr1,
    attr2: item1.attr2 + item2.attr2,
    attr3: item1.attr3 + item2.attr3
  }
})

如果对象属性较多、或者后续属性可能增减,可以用通用版本,自动遍历所有同名字段求和,不需要手动枚举每个属性:

const total = myArr1.map((item1, index) => {
  const item2 = myArr2[index]
  const res = {}
  for (const key of Object.keys(item1)) {
    res[key] = item1[key] + (item2[key] ?? 0)
  }
  return res
})

补充说明:之前写的const map1 = myArr1.map((item) => item);、const map2 = myArr2.map((item) => item);本质是对原数组做浅拷贝,和直接使用原数组的效果没有区别,不需要额外执行这两步操作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:42:51