0

I have an array of objects that's created dynamically (in React, although I don't think it matters), and I'm attempting to use addition on values that have the same name.

for example:

[{ n1:"1", n2:"2", n3:"3"},
 { n1:"4", n2:"6", n3:"4"},
 { n1:"3", n2:"1", n3:"2"}]

the result of which would then be:

[{ n1:"8", n2:"9", n3:"9"}]

Spread Syntax and the .assign method seem like they'd accomplish this, but both examples have predefined arrays, not dynamically created ones.

If it would be easier to parse the data so each name could occupy a new array, that'd be fine too. ie [n1:"8"],[n2:"9"],[n3:"9"]

ConJastle2
  • 13
  • 2
  • What have you tried so far? This could be done with a (`for` loop or `.forEach()` or `.reduce()`) + (`for...in...` or `Object.keys() or `Object.entries()`) – Andreas Jun 03 '20 at 08:10

2 Answers2

2

You could reduce the objects by creating a new object with the key/value pairs and add the value.

var data = [{ n1: "1", n2: "2", n3: "3"}, { n1: "4", n2: "6", n3: "4"}, { n1: "3", n2: "1", n3: "2"}],
    sums = data.reduce((target, source) => {
        Object.entries(source).forEach(([k, v]) => target[k] = (target[k] || 0) + +v);
        return target;    
    }, {});

console.log(sums);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Maybe a little bit terse, but using flatMap() and reduce():

const data = [
  {n1:"1", n2:"2", n3:"3"},
  {n1:"4", n2:"6", n3:"4"},
  {n1:"3", n2:"1", n3:"2"}
];

const result = data.flatMap(Object.entries)
                   .reduce((a, [k, v]) => (a[k] = (a[k] || 0) + +v, a), {});

console.log(result);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156