Grouping and Summing Objects in an Array
To group an array of objects by a specific property and sum up another property in jQuery, you can utilize the following steps:
1. Loop and Reduce:
Use the $.each() function to iterate over the array, and for each object, check if an object with the same grouping property already exists in the result array. If not, create a new object with the grouping property and an initial quantity of 0. Add this object to the result array.
2. Sum Up Properties:
Within the loop, add the value of the property you want to sum (e.g., qty) from the current object to the corresponding object in the result array. This effectively accumulates the quantities for each group.
Here's an example code using jQuery:
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 } ]; var result = []; $.each(array, function(i, obj) { var idx = result.findIndex(x => x.Id === obj.Id); if (idx === -1) { result.push({ Id: obj.Id, qty: 0 }); idx = result.length - 1; } result[idx].qty += obj.qty; }); console.log(result);
This code will log the following output:
[ { Id: "001", qty: 3 }, { Id: "002", qty: 2 }, { Id: "003", qty: 4 } ]
By following these steps, you can effectively group and sum the properties of objects in an array, enabling you to extract valuable insights from your data.
The above is the detailed content of How Can I Group and Sum Objects in an Array by a Specific Property Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!