Home >Web Front-end >JS Tutorial >How can I efficiently group and aggregate objects in an array by multiple properties?
Efficiently Grouping and Aggregating objects in an Array by Multiple Properties
In this article, we address a critical task: Grouping objects within an array by multiple properties and aggregating their values.
The Challenge
Grouping objects in arrays based on multiple criteria can be a perplexing problem. While existing solutions can group objects by multiple keys, they often fail to effectively combine and eliminate duplicates. Our goal is to create a solution that seamlessly groups objects by shape and color, sums their respective 'used' and 'instances' values, and eliminates duplicates.
The Solution
Our approach utilizes the array.reduce() method in conjunction with a helper object. For each object in the array, we construct a unique key by concatenating its shape and color. We then check if this key exists in our helper object:
By using a helper object to keep track of unique combinations of shape and color, we effectively group and aggregate objects while eliminating duplicates.
var 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} ]; var helper = {}; var result = arr.reduce(function(r, o) { var key = o.shape + '-' + o.color; if(!helper[key]) { helper[key] = Object.assign({}, o); // create a copy of o r.push(helper[key]); } else { helper[key].used += o.used; helper[key].instances += o.instances; } return r; }, []); console.log(result);
The Output
By implementing this solution, we obtain the desired result:
[{"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 effectively groups objects by shape and color, sums up their values, and removes duplicates.
The above is the detailed content of How can I efficiently group and aggregate objects in an array by multiple properties?. For more information, please follow other related articles on the PHP Chinese website!