Magno Alberto
Magno Alberto

Reputation: 668

Javascript : How group and sum values from multidimensional array

I have an array like this:

enter image description here

I would like to group and get the sum of each repetition like this:

Upvotes: 4

Views: 8016

Answers (5)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simple solution using Array.prototype.reduce function:

// Replace arr with your actual array!
var arr = [
        { AGENDADOR: 'AGE270', TOTAL : 6},
        { AGENDADOR: 'AGE270', TOTAL : 3},
        { AGENDADOR: 'AGE203', TOTAL : 5},
        { AGENDADOR: 'AGE028', TOTAL : 9},
    ],
  
  totals = arr.reduce(function (r, o) {
    (r[o.AGENDADOR])? r[o.AGENDADOR] += o.TOTAL : r[o.AGENDADOR] = o.TOTAL;
    return r;
  }, {});

console.log(totals);

arr.reduce(callback, [initialValue])

initialValue

Optional. Value to use as the first argument to the first call of the callback.

Upvotes: 13

Nils
Nils

Reputation: 969

How about a simple map() function? Like this:

var t = YourArray;
var u = t.map(function (a, i) { var g = {}; g[a.AGENDADOR] = a.TOTAL; return g; });

Upvotes: 0

dev8080
dev8080

Reputation: 4020

Try this out:

function( data ){
        var outputObj = {} ;
        for(var i=0;i < data.length; i++){
                 datum = data[i];
                 if(outputObj[datum.AGENDADOR])
                         outputObj[datum.AGENDADOR] += parseInt( datum.TOTAL) ;
                 else
                         outputObj[datum.AGENDADOR] = parseInt( datum.TOTAL);
                }

        return outputObj;

};

Upvotes: 0

Valentin Coudert
Valentin Coudert

Reputation: 1919

var sum = {};

yourArray.forEach(function(item) {
  if(sum[item.AGENDADOR] === undefined) {
    sum[item.AGENDADOR] = 0;
  }

  sum[item.AGENDADOR] += item.TOTAL  
});

With this code, you'll have the total corresponding to each key in the sum object. Something like this:

{
  AGE270: 9,
  AGE203: 5,
  AGE208: 9
} 

Upvotes: 0

cdhowie
cdhowie

Reputation: 168958

Using lodash:

var data; // the data represented by your screenshot

var counts = _.chain(data)
    .groupBy('AGENDADOR')
    .map(_.size)
    .value();

counts will now be an object like this:

{
    "AGE270": 9,
    "AGE203": 5,
    // etc
}

Upvotes: 0

Related Questions