最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript : How group and sum values from multidimensional array - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question edited Jan 27, 2017 at 18:52 zx485 29k28 gold badges52 silver badges63 bronze badges asked Jan 27, 2017 at 18:36 Magno AlbertoMagno Alberto 66816 silver badges28 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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.

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

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;

};

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; });
发布评论

评论列表(0)

  1. 暂无评论