Home >Web Front-end >JS Tutorial >How to Group and Sum an Array of Objects by a Property Using jQuery?
Given an array of objects, your goal is to group them by a specific property, such as Id, and calculate the sum of another property, such as qty, for each group using jQuery.
Consider the following input array:
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 } ];
The desired output is:
[ { Id: "001", qty: 3 }, { Id: "002", qty: 2 }, { Id: "003", qty: 4 } ]
To group the array by Id and sum the qty values for each group using jQuery, you can employ the following approach:
$(array).groupBy('Id').reduce(function (res, obj) { return res + obj.qty; }, 0);
Here's a breakdown of the solution:
The above is the detailed content of How to Group and Sum an Array of Objects by a Property Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!