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

Mag*_*rto 2 javascript multidimensional-array

我有这样一个数组:

在此输入图像描述

我想分组并获得每次重复的总和,如下所示:

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

Rom*_*est 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);
Run Code Online (Sandbox Code Playgroud)

arr.reduce(callback, [initialValue])

初始值

Optional. Value to use as the first argument to the first call of the callback.
Run Code Online (Sandbox Code Playgroud)