Reputation: 668
I have an array like this:
I would like to group and get the sum of each repetition like this:
Upvotes: 4
Views: 8016
Reputation: 92854
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.
Upvotes: 13
Reputation: 969
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; });
Upvotes: 0
Reputation: 4020
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;
};
Upvotes: 0
Reputation: 1919
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
}
Upvotes: 0