javascript—数组中每个项的单位总和

lyfkaqu1  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(253)

此问题已在此处找到答案

如何对对象数组进行分组和求和[(2份答案)
4小时前关门了。
我试图找到数组中每件商品的总销售额,如下所示:
数组看起来像:

{ 
  [
    'Some Title Item', '22', 'Apple'
  ],
  [
    'Another Item', '12', 'Android'
  ],
  [
    'Third Item', '15', 'Android'
  ], 
  [
    'Another Item', '6', 'Apple'
  ],...
}

我已经有了一个变量,我存储了所有的标题/标签,现在需要找到每个标题/标签的总销售额。因此,所需的输出类似于:

{
 ['Some Title Item', '45'], ['Another Item', '32'], ['Third Item', '85'], ...
}

我尝试过两个双层循环(i&j),但它们非常昂贵,而且肯定不是这种情况下的最佳方法,但我想不出更好的方法。非常感谢你的帮助!

wlzqhblo

wlzqhblo1#

您的输入和输出必须是数组。
使用 array.reduce 为了达到你想要的结果。

const data = [
  [
    'Some Title Item', '22', 'Apple'
  ],
  [
    'Another Item', '12', 'Android'
  ],
  [
    'Third Item', '15', 'Android'
  ],
  [
    'Another Item', '6', 'Apple'
  ]
];
let output = [];
output = data.reduce((acc, curr) => {
  const node = acc.find((node) => node[0] === curr[0]);
  if (node) {
    node[1] += Number(curr[1]);
  } else {
    acc.push([curr[0], Number(curr[1])]);
  }
  return acc;
}, []);
console.log(output);

相关问题