4

I have an array like this:

enter image description here

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

  • AGE270: 9
  • AGE203: 5
  • AGE208: 9
  • ...
  • AGEXXX: n

5 Answers 5

13

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, worked perfectly, however, what is this "{}" for in the end? I did a test without and of course the result was not as expected.
@MagnoAlberto, it's called initialValue. I've cited from documentation as explanation
The thing is that you ended with a different object, not the same as the original but grouped.
0

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
}

Comments

0
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
} 

Comments

0

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;

};

Comments

0

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; });

2 Comments

Thanks, But it did not work, I thought I'd get with "map", of course, that your code was better than mine.
Have a look at Romans answer, reduce should work very good as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.