Javascript:多维数组中的group和sum值如何

时间:2017-01-27 18:36:25

标签: javascript multidimensional-array

我有一个这样的数组:

enter image description here

我想分组并得到每次重复的总和:

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

5 个答案:

答案 0 :(得分:7)

使用Array.prototype.reduce函数的简单解决方案:



// 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])

     

<强> 初值

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

答案 1 :(得分:0)

使用lodash

var data; // the data represented by your screenshot

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

counts现在将成为这样的对象:

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

答案 2 :(得分:0)

var sum = {};

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

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

使用此代码,您将拥有与sum对象中每个键对应的总数。像这样:

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

答案 3 :(得分:0)

试试这个:

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;

};

答案 4 :(得分:0)

一个简单的map()函数怎么样?像这样:

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