Group objects by multiple properties in array then sum up their values Group objects by multiple properties in array then sum up their values arrays arrays

Group objects by multiple properties in array then sum up their values


Use Array#reduce with a helper object to group similar objects. For each object, check if the combined shape and color exists in the helper. If it doesn't, add to the helper using Object#assign to create a copy of the object, and push to the array. If it does, add it's values to used and instances.

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);