venom venom - 2 months ago 6
Javascript Question

sum values in object if multiple keys are the same JS

for example i have 5 objects:

{ row: aa, col: 1, value: 1 }
{ row: bb, col: 2, value: 1 }
{ row: bb, col: 3, value: 1 }
{ row: aa, col: 1, value: 1 }
{ row: aa, col: 2, value: 1 }


i want to sum values if row and col are the same, so the output should be:

{ row: aa, col: 1, value: 2 }
{ row: bb, col: 2, value: 1 }
{ row: bb, col: 3, value: 1 }
{ row: aa, col: 2, value: 1 }


thank you for your help!

tried this:
Sum javascript object propertyA values with same object propertyB in array of objects

Answer

You can do this with reduce() and one object to store keys.

var data = [
  { row: 'aa', col: 1, value: 1 },
  { row: 'bb', col: 2, value: 1 },
  { row: 'bb', col: 3, value: 1 },
  { row: 'aa', col: 1, value: 1 },
  { row: 'aa', col: 2, value: 1 }
]

var o = {}
var result = data.reduce(function(r, e) {
  var key = e.row + '|' + e.col;
  if (!o[key]) {
    o[key] = e;
    r.push(o[key]);
  } else {
    o[key].value += e.value;
  }
  return r;
}, []);

console.log(result)

Comments