按多个属性对数组中的元素进行分组 https://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties是与我的问题最接近的匹配,因为它确实通过数组中的多个键对对象进行分组。问题是这个解决方案不会对属性值求和然后删除重复项,而是将所有重复项嵌套在二维数组中。
预期行为
我有一个对象数组,必须按以下方式分组shape
and color
.
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}
];
仅当此数组中的对象都是重复的时,才将其视为重复项shape
and color
是相同的。如果是的话我想分别总结一下used
and instances
值,然后删除重复项。
因此,在此示例中,结果数组可能仅包含四种组合:square red
, square blue
, circle red
, circle blue
Problem
我在这里尝试了一种更简单的方法:
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: 'red', used: 4, instances: 4},
{shape: 'square', color: 'red', used: 2, instances: 2}
];
result = [];
arr.forEach(function (a) {
if ( !this[a.color] && !this[a.shape] ) {
this[a.color] = { color: a.color, shape: a.shape, used: 0, instances: 0 };
result.push(this[a.color]);
}
this[a.color].used += a.used;
this[a.color].instances += a.instances;
}, Object.create(null));
console.log(result);
但它输出
[{shape: "square", color: "red", used: 11, instances: 9},
{shape: "circle", color: "blue", used: 4, instances: 4}]
而不是预期的结果:
[{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}]
如何让我的函数按形状和颜色正确对对象进行分组?即总结它们的值并删除重复项?