Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : How group and sum values from multidimensional array

I have an array like this:

enter image description here

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

  • AGE270: 9
  • AGE203: 5
  • AGE208: 9
  • ...
  • AGEXXX: n
like image 746
Magno Alberto Avatar asked Dec 14 '22 01:12

Magno Alberto


1 Answers

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.
like image 121
RomanPerekhrest Avatar answered Mar 22 '23 23:03

RomanPerekhrest