Grouping and Summing an Array of Objects by a Key
In JavaScript, you can group an array of objects by a specific key and sum the values associated with that key using jQuery's powerful tools. Here's how you can achieve this:
var array = [ { Id: '001', qty: 1 }, { Id: '002', qty: 2 }, { Id: '001', qty: 2 }, { Id: '003', qty: 4 } ];
Looping and Summing
One effective method is to iterate through the array and accumulate the values using the reduce() method. This method takes a callback function that reduces the array to a single value, in this case, an object representing the grouped values.
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; }, {});
Output:
[ { Id: '001', qty: 3 }, { Id: '002', qty: 2 }, { Id: '003', qty: 4 } ]
This solution efficiently groups the objects by the Id key and sums the corresponding qty values, resulting in an array of objects with grouped and summed values.
The above is the detailed content of How to Group and Sum an Array of Objects by a Key in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!