Javascript 如何对对象数组进行分组和求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29364262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:15:56  来源:igfitidea点击:

how to group by and sum array of object?

javascriptarrays

提问by Phirum

I would like to Group Object of Array by Id and sum by quantity in Jquery? For example:

我想在 Jquery 中按 Id 对数组对象进行分组并按数量求和?例如:

var array = [
  { Id: "001", qty: 1 },
  { Id: "002", qty: 2 },
  { Id: "001", qty: 2 },
  { Id: "003", qty: 4 }
]

After I Group it by the Id I will get the new Array like:

在我按 Id 对它进行分组后,我将得到新的数组,如:

 [
    { Id: "001", qty: 3 },
    { Id: "002", qty: 2 },
    { Id: "003", qty: 4 }
 ]

回答by Arun P Johny

You can loop and sum it up

你可以循环并总结

var array = [
  { Id: "001", qty: 1 }, 
  { Id: "002", qty: 2 }, 
  { Id: "001", qty: 2 }, 
  { Id: "003", qty: 4 }
];

var result = [];
array.reduce(function(res, value) {
  if (!res[value.Id]) {
    res[value.Id] = { Id: value.Id, qty: 0 };
    result.push(res[value.Id])
  }
  res[value.Id].qty += value.qty;
  return res;
}, {});

console.log(result)

Fiddle: Fiddle

小提琴:小提琴

回答by Sadikhasan

var newArr = [];

$.each(array,function(index,element){
    if(newArr[element.Id]==undefined){
        newArr[element.Id] =0;
    }
    newArr[element.Id] += element.qty;
});
console.log(newArr);

Demo

演示