David Morales Vega
David Morales Vega

Reputation: 23

How to group the first value (string) and add the values of the same dates?

JAVASCRIPT - JQUERY sum the values How to group the first value (the date) and add the values of the same dates?

ARRAY :

0: (5) ["11-2019", 0, 20, 0, 0]
1: (5) ["11-2019", 41, 0, 0, 0]
2: (5) ["11-2019", 0, 0, 29, 0]
3: (5) ["11-2019", 0, 0, 0, 60]
4: (5) ["09-2019", 0, 1, 0, 0]
5: (5) ["09-2019", 0, 0, 1, 0]
6: (5) ["09-2019", 0, 0, 0, 1]
7: (5) ["05-2019", 2, 0, 0, 0]

OUT :

0: (5) ["11-2019", 41, 20, 29, 60]
1: (5) ["09-2019", 0, 1, 1, 1]
2: (5) ["05-2019", 2, 0, 0, 0]

result = DataAll.reduce(function(r, a) {
     a.forEach(function(b, i) {

         r[i] = (r[i] || 0) + b;
         console.log(r[i]);
     });
     return r;
 }, []);

Upvotes: 1

Views: 59

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

I added a filter to your script to remove the 0-values from the results. If you really want the 0 values use

acc[curr[0]]=(acc[curr[0]]||[]).concat(curr.slice(1));

instead.

var inp=[["11-2019", 0, 20, 0, 0],
 ["11-2019", 41, 0, 0, 0],
 ["11-2019", 0, 0, 29, 0],
 ["11-2019", 0, 0, 0, 60],
 ["09-2019", 0, 1, 0, 0],
 ["09-2019", 0, 0, 1, 0],
 ["09-2019", 0, 0, 0, 1],
 ["05-2019", 2, 0, 0, 0]];
 var out=inp.reduce((acc,curr)=>{
   acc[curr[0]]=(acc[curr[0]]||[]).concat(curr.slice(1).filter(v=>v>0));
   return acc
 }, {});
  console.log(out);
  
  // and to get it into your format:
  var outarr=Object.keys(out).map(k=>[k].concat(out[k]))
  console.log(outarr)

Right, if you want the sum then my version would be the following. Thanks to Nina for supplying a correct answer first. ;-)

var inp=[["11-2019", 0, 20, 0, 0],
 ["11-2019", 41, 0, 0, 0],
 ["11-2019", 0, 0, 29, 0],
 ["11-2019", 0, 0, 0, 60],
 ["09-2019", 0, 1, 0, 0],
 ["09-2019", 0, 0, 1, 0],
 ["09-2019", 0, 0, 0, 1],
 ["05-2019", 2, 0, 0, 0]];
 
 let out=inp.reduce((acc,cur)=>{
   if(acc[cur[0]]) acc[cur[0]].forEach((v,i,a)=>a[i]+=cur[i+1]);
   else acc[cur[0]]=cur.slice(1)
   return acc
 }, {} );
 outarr=Object.keys(out).map(k=>[k].concat(out[k]))
 
 console.log(outarr)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386522

I would find the array in the result set and update all values.

var data = [["11-2019", 0, 20, 0, 0], ["11-2019", 41, 0, 0, 0], ["11-2019", 0, 0, 29, 0], ["11-2019", 0, 0, 0, 60], ["09-2019", 0, 1, 0, 0], ["09-2019", 0, 0, 1, 0], ["09-2019", 0, 0, 0, 1], ["05-2019", 2, 0, 0, 0]],
    result = data.reduce((r, a) => {
        var temp = r.find(([date]) => date === a[0])
        if (temp) {
            for (var i = 1; i < a.length; i++) temp[i] += a[i];
        } else {
            r.push([...a]);
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions