-1

I have this one array with multiple arrays in it, containing objects (responses from HTTP requests)

The big array:

datas = [
   [
     {
       data: {
         pid: 107,
         value: 5
       }
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 42
       }
     }
   ],
   [
     {
       data: {
         pid: 107,
         value: 64
       }
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 322
       }
     }
   ]
]

Ok, so how could I make a new array (or object) grouped by pid and a sum with values assigned to pid? It is not the typical question with a SUM by property inside array of arrays.

What I have tried:

 datas.forEach((d,k1) => { 
   d.forEach((e,k2) => {
   total += e.data.value
   newArr[k2] = total;
  })
})
Tudor-Radu Barbu
  • 444
  • 1
  • 11
  • 28
  • 4
    It is well received to always include what you have tried so far... – Shidersz Mar 06 '19 at 17:08
  • 2
    You should also show what output you expect. Note that there are many questions with similar titles; you'll want to say how yours differs. For example, [Sum of array object property values in new array of objects in Javascript](https://stackoverflow.com/q/37481539/215552) – Heretic Monkey Mar 06 '19 at 17:10
  • It is not a just the typical question - make the sum of a property in an array. C'mmon. – Tudor-Radu Barbu Mar 06 '19 at 17:11

1 Answers1

2

You could use Array.prototype.reduce with an inner Array.prototype.forEach to iterate over the inner arrays and group PIDs into an Object:

const data = [
   [
     {
       data: {
         pid: 107,
         value: 5
       },
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 42
       }
     }
   ],
   [
     {
       data: {
         pid: 107,
         value: 64
       },
       status: 200
     },
     {
       data: {
          pid: 108,
          value: 322
       }
     }
   ]
];

const merged = data.reduce((merged, innerArr) => {
  innerArr.forEach(({data}) => {
    merged[data.pid] = (merged[data.pid] || 0) + data.value;
  });
  return merged;
}, {});

console.log(merged);
Scott Rudiger
  • 1,224
  • 12
  • 16