[removed] How group and sum values from multidimensional array

前端 未结 5 627
广开言路
广开言路 2020-12-21 10:10

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
相关标签:
5条回答
  • 2020-12-21 10:28
    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
    } 
    
    0 讨论(0)
  • 2020-12-21 10:30

    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
    }
    
    0 讨论(0)
  • 2020-12-21 10:33

    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 讨论(0)
  • 2020-12-21 10:36

    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.
    
    0 讨论(0)
  • 2020-12-21 10:43

    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;
    

    };

    0 讨论(0)
提交回复
热议问题