通过多个属性对数组中的对象进行高效分组和聚合
在本文中,我们将解决一项关键任务:对数组中的对象进行分组通过多个属性并聚合它们的值。
挑战
根据多个条件对数组中的对象进行分组可能是一个令人困惑的问题。虽然现有的解决方案可以通过多个键对对象进行分组,但它们通常无法有效地组合和消除重复项。我们的目标是创建一个解决方案,可以按形状和颜色对对象进行无缝分组,对它们各自的“已使用”和“实例”值进行求和,并消除重复项。
解决方案
我们的方法将 array.reduce() 方法与辅助对象结合使用。对于数组中的每个对象,我们通过连接其形状和颜色来构造一个唯一的键。然后,我们检查辅助对象中是否存在此键:
通过使用辅助对象来跟踪形状和颜色的独特组合,我们可以有效地对对象进行分组和聚合,同时消除重复项。
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);
输出
通过实施此解决方案,我们获得了所需的结果:
[{"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}]
这可以有效地按形状和颜色对对象进行分组,总结它们的值,并删除重复项。
以上是如何通过多个属性有效地对数组中的对象进行分组和聚合?的详细内容。更多信息请关注PHP中文网其他相关文章!