Fares K. A. Fares K. A. - 3 months ago 13
Javascript Question

JavaScript: Grouping Objects w/ Similar Attributes

I have an array of JavaScript objects, that look something like this.

[ { name: "A", value: 50 },
{ name: "B", value: 20 },
{ name: "C", value: 30 },
{ name: "A", value: 40 },
{ name: "A", value: 50 },
{ name: "B", value: 70 },
{ name: "A", value: 10 },
{ name: "C", value: 50 } ]


I want to loop through this array and remove any duplicate objects of the same name, while adding their values together. In basic terms:

[ { name: "A", value: 200 },
{ name: "B", value: 90 },
{ name: "C", value: 80 } ]


I have an idea of how to go about this, pseudo-code:

for each object Obj in array A
current = Obj
for(i = (Obj's index + 1); i < A.length; i++)
if(A[i].name = Obj.name)
Obj.value += A[i].value
delete A[i]
endif
endfor
endfor


I feel this is very inefficient. Is there any better way of going about this?

Answer

You can use the reduce function.

Note that for simplicity the sums are gathered as an associative array (grouped by name) and then the values retrieved to match your expected result.

var arr = [ { name: "A", value: 50 },
  { name: "B", value: 20 }, 
  { name: "C", value: 30 }, 
  { name: "A", value: 40 }, 
  { name: "A", value: 50 }, 
  { name: "B", value: 70 }, 
  { name: "A", value: 10 }, 
  { name: "C", value: 50 } ];

var sums = arr.reduce(function (acc, curr) { 
  if(acc[curr.name]) {
    acc[curr.name].value += curr.value;
  } else {
    acc[curr.name] = curr;
  }
  
  return acc;
}, {});

var res = Object.keys(sums).map(function (key) {
    return sums[key];
});

console.log(res);