Reputation: 321
I have an array of daily data like below:
var data = [{x: '2017-01-01', y: 100}, {x: '2017-01-02', y: 99}, /* whole year. */];
Each element has a x field which is date, y field which is number. The array contains such data of a whole year.
I am expecting an output of array where each element is a sum of y in every month like:
var output = [10000, 9999, ...]
I am not sure if javascript has a function like 'GROUP BY' in SQL, if yes, then maybe I can use some reduce method to accumulate data of every month. Can you please help?
Upvotes: 1
Views: 75
Reputation: 386654
You could use a result set with for all month with zero values and then iterate the data, take the month, make it zero based and usit as index for adding the value of each item.
var data = [{ x: '2017-01-01', y: 100 }, { x: '2017-01-02', y: 99 }, { x: '2017-01-02', y: 99 }, { x: '2017-02-02', y: 10 }, { x: '2017-04-02', y: 42 }],
result = Array.apply(null, { length: 12 }).map(function () { return 0; });
data.forEach(function (o) {
result[o.x.slice(5, 7) - 1] += o.y;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2