I have JSON data:
var data = [ { dat: 'timestamp', val: 10 }, { dat: 'timestamp', val: 20}, (...)]
Data contains objects with timestamp and value, can be more than one in month.
I need to sum values from objects which have the same month and year.
First I use each function to add additional field cat
which contains formatted date in format MMM'YY
for example: Sep'15
, after that I group the result by this cat
field. This result I map to objects with properties name
and value
. Values are summed by using reduce
function on plucked values - val
from each grouped result. I'm using underscore.
var withCategories = _.each(data, function (elem) {
elem.cat = moment(elem.dat).format("MMM[']YY");
});
var groupedResult = _.groupBy(withCategories , 'cat');
var finalResult = _.map(groupedResult, function (elems) {
var valuesArray = _.pluck(elems, 'val'); // from group
return {
name: elems[0] ? elems[0].cat : '',
value: _.reduce(valuesArray, function (memo, num) {
return memo + num;
}, 0)
}
});