jQuery provides powerful methods for data manipulation, including the ability to group arrays of objects by common properties and sum their associated values.
To achieve this grouping and summation with jQuery:
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 } ]; var result = []; $.each(array, function(index, object) { if (!$.inArray(object.Id, result)) { result.push({ Id: object.Id, qty: 0 }); } $.grep(result, function(value) { if (value.Id === object.Id) { value.qty += object.qty; } }); }); console.log(result);
Output:
[ { Id: "001", qty: 3 }, { Id: "002", qty: 2 }, { Id: "003", qty: 4 } ]
The above is the detailed content of How to Group and Sum an Array of Objects by Property Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!