【问题标题】:Calculate the sum of values within an array of objects [duplicate]数组中每个项目的单位总和[重复]
【发布时间】:2021-10-03 04:17:21
【问题描述】:

我正在尝试查找数组中销售的每件商品的总和,如下所示:

数组看起来像:

 { 
  [
    '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),但它们非常昂贵,而且绝对不是这种情况下的最佳方法,但我想不出更好的方法。非常感谢您的帮助!

【问题讨论】:

标签: javascript arrays reactjs loops


【解决方案1】:

您的输入和输出必须是数组。

使用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);

【讨论】:

    猜你喜欢
    • 2013-08-20
    • 2017-05-26
    • 2020-05-17
    • 2019-06-12
    • 2013-02-04
    • 2016-12-21
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多