根据条件对二维数组中的多个项目求和(javascript)

问题描述 投票:0回答:1

我有一个二维数组:

[ [ 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 ]]

匹配每个数组中的第一个索引,并对其他索引求和。

我的第一个想法是使用 reducefindIndex 查找第一项的索引,如果找不到,则将项添加到数组,否则将值求和。

但是我真的不知道自己在做什么。

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},[]);

请帮忙!

javascript arrays multidimensional-array conditional-statements sum
1个回答
0
投票

使用

reduce
是一个很好的方法,但是在您的尝试中,您永远不会更新累加器
acc
:回调始终返回相同的、未突变的
acc
数组。

这是使用reduce 实现此目的的一种方法:

const arr = [ [ 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 = Object.values(
    arr.reduce((acc, [key, ...rest]) => {
        if (!acc[key]) acc[key] = [key, ...rest];
        else rest.forEach((val, i) => (acc[key][i+1] += val));
        return acc;
    }, {})
);
console.log(result);

© www.soinside.com 2019 - 2024. All rights reserved.