I have lists of arrays like this:
var a = [
{ month: 'January', count: 3 },
{ month: 'February', count: 5 },
{ month: 'March', count: 4 }
];
var b = [
{ month: 'January', count: 4 },
{ month: 'February', count: 5 },
{ month: 'March', count: 1 }
];
And I want to create a "total" list, using Underscore, that looks like this:
var totals = [
{ month: 'January', count: 7 },
{ month: 'February', count: 10 },
{ month: 'March', count: 5 }
];
I don't know in advance what the values of "month" will be, so I need to allow for this.
This is as far as I've got, but it's not very elegant. Is there a nicer way?
var totals = [];
_.each([a, b], function(d) {
_.each(items, function(e) {
var matchingItem = _.filter(totals, function(item, i) {
return (item.month === e.month);
});
if (matchingItem) {
var i = totals.indexOf(matchingItem);
totals[i].count += e.count;
} else {
var newItem = e;
totals.push(e);
}
});
};