如何计算数组中项的总和?

时间:2019-03-29 02:32:10

标签: javascript arrays

假设我有一个数组:

const items = [
  {
    "amount1": "100",
    "amount2": "50",
    "name": "ruud"
  },
  {
    "amount1": "40",
    "amount2": "60",
    "name": "ted"
  }
]

我想要总计所有的amount1和amount2道具,结果是:

[
  {
    "amount1": 140,
    "amount2": 110
  }
]

我该怎么做?

6 个答案:

答案 0 :(得分:3)

Array.prototype.reduce()Object.entries()Array.prototype.forEach()结合使用:

const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];

const sums = items.reduce((acc, item) => {
  Object.entries(item).forEach(([k, v]) => acc[k] = (acc[k] || 0) + v);
  return acc;
}, {});

console.log(sums);

filter排除非数字属性(但根据更新的问题保留带引号的数字字符串):

const items = [{amount1: '100', amount2: '50', name: 'Ruud'}, {amount1: '40', amount2: '60', name: 'Ted'}];

const sums = items.reduce((acc, item) => {
  Object.entries(item)
        .filter(([_, v]) => !isNaN(v))
        .forEach(([k, v]) => acc[k] = (acc[k] || 0) + Number(v));
  return acc;
}, {});

console.log(sums);

答案 1 :(得分:1)

您可以使用reduce()

  • 在数组reduce()上使用items方法
  • 将累加器(ac)设置为空对象,即{}
  • 在每次对象迭代期间,创建一个for..in循环以迭代对象的所有键。
  • 检查typeof的{​​{1}}值是否为key,然后添加它,否则不要添加

"number"

答案 2 :(得分:0)

reduce()确实是可行的方法,但最简单的方法是仅通过一组已知键进行操作,可能会将您的预期结果作为累加器传递并遍历该累加器的键:

const items = [
  { amount1: "100", amount2: "50", name: "ruud", foo: "unrelated" },
  { amount1: "40", amount2: "60", name: "ted", foo: "0" }
];

const result = items.reduce((acc, item) => {
  for (let key in acc) { // iterate over the accumulator's keys
    acc[key] += isNaN(item[key]) ? 0 : +item[key];
  }
  return acc;
}, { // here we define the expected format
  amount1: 0,
  amount2: 0
});

console.log(result);

答案 3 :(得分:0)

const items = [{amount1: 100, amount2: 50}, {amount1: 40, amount2: 60}];
function sum(data){
 const keys =  Object.keys(data[0])
 let res = {}
 for(key of keys)
   res[key]=data.map(x=>x[key]).reduce((a,b)=>a+b);
return res
  
}

console.log(sum(items))

答案 4 :(得分:0)

这是一种替代,简单且干净的解决方案。

const items = [{amount1:100, amount2:50, name:"ruud"},{amount1:40,amount2:60,name:"ted"}]
let result = [{amount1:0,amount2:0}]
items.forEach(i=>{
  result[0].amount1 += i.amount1
  result[0].amount2 += i.amount2
})
console.log(result)

答案 5 :(得分:0)

上述解决方案很棒。如果您不想使用,我将其包括在内  Array.prototype.reduce()。即使您拥有其他不是“数字”的属性,这也将起作用

 const items = [{amount1: 100, amount2: 50, name: 'Ruud'}, {amount1: 40, amount2: 60, name: 'Ted'}];
 var result = {};

 items.forEach(function(eachItem){
    for(var prop in eachItem){
        if(typeof eachItem[prop] === "number"){
           result[prop] = result[prop] ? result[prop] + eachItem[prop] : eachItem[prop];                 
        }                
     }
 });
 result = [result];
 console.log(result);