-1

How can I group by month and add the values ​​according to the position of this object?

original = {"data":[["Dic",0,0,165,0],["Ene",0,0,200,0],["Ene",150,0,0,0],["Ene",150,20,10,500]]}

what i need = {"data":[["Dic",0,0,165,0],["Ene",300,20,210,500]]}
  • This seems rather elementary, what have you tried? Given that you don't have a massive amount of data (i.e. that you don't need very much optimization), make a dictionary that keeps track of the result, and a loop that goes through your list and updates said dictionary with the values it encounters. – Roope Jan 25 '18 at 15:03
  • Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – GG. Jan 25 '18 at 15:07

1 Answers1

1

Create a temporary object to group the items using the first array element values as keys. Then map new values each iteration

const original = {"data":[["Dic",0,0,165,0],["Ene",0,0,200,0],["Ene",150,0,0,0],["Ene",150,20,10,500]]}

const tmp = original.data.reduce((a,c)=>{
   a[c[0]] = (a[c[0]] ||  [c[0],0,0,0,0]).map((el,i)=> i ? el + c[i] :el);
   return a;   
}, {});

original.data = Object.keys(tmp).map(key => tmp[key]);

console.log(JSON.stringify(original))
charlietfl
  • 170,828
  • 13
  • 121
  • 150