Grouping and Summing an Array of Objects in jQuery: A Detailed Guide
Grouping and summing values in an array of objects is a common task in programming. In jQuery, this can be achieved efficiently using the reduce() method.
Understanding the Goal
The aim is to group an array of objects based on a specific property, in this case, the "Id" property. Once the objects are grouped, the quantity ("qty") of each group should be summed up.
Step-by-Step Solution
Loop Through the Array: Use the reduce() method to iterate through the array. This method takes two functions as parameters:
Example Implementation
The following jQuery code snippet demonstrates the steps outlined above:
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);
This code will output the following grouped and summed array of objects:
[ { Id: "001", qty: 3 }, { Id: "002", qty: 2 }, { Id: "003", qty: 4 } ]
The above is the detailed content of How Can You Group and Sum an Array of Objects in jQuery Using the Reduce Method?. For more information, please follow other related articles on the PHP Chinese website!