Grouping Objects by Multiple Properties and Aggregating Values
In the task of grouping objects in an array by multiple properties, a common requirement is to not only group by these properties but also sum up the values of certain object properties. However, a solution that simply nests all duplicates in a two-dimensional array is insufficient.
Problem Statement
Consider an array of objects that must be grouped by shape and color. Objects in this array are considered duplicates only if both their shape and color are the same. For duplicate objects, we need to sum up their used and instances values and remove the duplicates, resulting in a concise list of objects with unique shapes and colors.
Solution
To effectively solve this problem, we can leverage the Array#reduce method in conjunction with a helper object that tracks encountered shape and color combinations:
const arr = [ { shape: 'square', color: 'red', used: 1, instances: 1 }, { shape: 'square', color: 'red', used: 2, instances: 1 }, { shape: 'circle', color: 'blue', used: 0, instances: 0 }, { shape: 'square', color: 'blue', used: 4, instances: 4 }, { shape: 'circle', color: 'red', used: 1, instances: 1 }, { shape: 'circle', color: 'red', used: 1, instances: 0 }, { shape: 'square', color: 'blue', used: 4, instances: 5 }, { shape: 'square', color: 'red', used: 2, instances: 1 }, ]; const helper = {}; const result = arr.reduce((r, o) => { const key = `${o.shape}-${o.color}`; if (!helper[key]) { // If it's a unique combination, add to the helper and result array helper[key] = Object.assign({}, o); r.push(helper[key]); } else { // If it's a duplicate, update the values in the helper helper[key].used += o.used; helper[key].instances += o.instances; } return r; }, []); console.log(result);
Output:
[ { shape: "square", color: "red", used: 5, instances: 3 }, { shape: "circle", color: "red", used: 2, instances: 1 }, { shape: "square", color: "blue", used: 11, instances: 9 }, { shape: "circle", color: "blue", used: 0, instances: 0 } ]
This solution efficiently groups the objects by shape and color, aggregates their used and instances values for duplicate objects, and removes any remaining duplicates, resulting in the desired output.
The above is the detailed content of How to Group Objects by Multiple Properties and Aggregate Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!