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

问题描述:

我有一个这样的数组:

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

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


  • AGE270:9

  • AGE203:5

  • AGE208:9

  • ...

  • AGEXXX:n

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

使用 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(回调,[initialValue])

initialValue

initialValue

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