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

如何在JavaScript中按条件对二维数组的多项求和?

按子数组首元素分组求和的实现与问题排查

输入数组

[ [ 1, 2, 43, 5 ],
  [ 1, 5, 12, 1 ],
  [ 2, 3, 6, 77 ],
  [ 2, 1, 48, 94 ],
  [ 3, 3, 15, 85 ],
  [ 3, 7, 97, 86 ],
  [ 4, 0, 9, 54 ],
  [ 4, 1, 83, 16 ]]

期望结果

[ [ 1, 7, 55, 6 ],
  [ 2, 4, 54, 171 ],
  [ 3, 10, 112, 171 ],
  [ 4, 1, 92, 70 ]]

需求说明

根据每个子数组的第一个元素进行分组,对同组内子数组的其余对应位置元素分别求和。

最初错误实现

array.reduce((acc,e) => 
      { let index = acc.findIndex(inner => inner[0] === e[0]);
      (index === -1) ? [...acc,e] : (acc[index][1] += e[1]) && (acc[index][2] += e[2]) && (acc[index][3] += e[3]);
      return acc},[]);

问题原因

这段代码中,当找不到对应分组时,[...acc,e]生成了包含当前元素的新数组,但这个新数组没有被用来更新累加器acc——三元运算符的结果仅被计算,却未改变原acc的状态。而reduce的迭代依赖每次返回的acc,原acc始终没有新增元素,导致后续findIndex永远找不到匹配项,无法完成分组求和。

修正后的正确实现

const input = [ [ 1, 2, 43, 5 ],
              [ 1, 5, 12, 1 ],
              [ 2, 3, 6, 77 ],
              [ 2, 1, 48, 94 ],
              [ 3, 3, 15, 85 ],
              [ 3, 7, 97, 86 ],
              [ 4, 0, 9, 54 ],
              [ 4, 1, 83, 16 ]]; 

const result = input.reduce((acc,e) => 
    { let index = acc.findIndex(inner => inner[0] === e[0]);
    (index === -1) ? acc.push(e) : (acc[index][1] += e[1]) && (acc[index][2] += e[2]) && (acc[index][3] += e[3]);
    return acc;
    },[]); 

console.log(result);

修正逻辑

将[...acc,e]替换为acc.push(e),push方法会直接修改原累加器数组acc,把当前元素添加进去。后续迭代时,acc已包含之前的分组,findIndex能正确找到对应分组的索引,进而完成对应位置元素的求和操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:50:08