Javascript : How group and sum values from multidimensional array

a 夏天 提交于 2019-12-29 09:09:31

问题


I have an array like this:

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

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

回答1:


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.



回答2:


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
}



回答3:


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
} 



回答4:


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;

};




回答5:


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


来源:https://stackoverflow.com/questions/41900798/javascript-how-group-and-sum-values-from-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!