Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object group by day,month,year

I am working on application which I need to do grouping of different sets of javascript object and those will be based on month,day and year.

For day I am doing like below

var calculateByDay = function(inputList){
        var outPutList = [];    
        var result = {}
        var item = null, key = null;
        for(i=0; c<inputList.length; i++) {
           item=inputList[c];
           key = Object.keys(item)[0];
           item=item[key];
           if(!result[key]) {
                result[key] = item;
            }
           else {
            result[key] += item;
        }
        for (r in result)
            {
                var docs = {};
                docs["date"] = r;
                docs["amount"] = result[r];
                outPutList.push(docs);
            }

        }
        return outPutList;
    }

How can I improve above code and use it for month and year calculation also? I went thorough underscore.js and it has a groupBy method. but seems not fits with my requirement. I want to group by months and year also, for

var inputList = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];

The output should be:

Monthly :
[{"December 2012": 2000}, {"January 2013": 1200},{"February 2013": 1550}];
Yearly
[{"year 2012": 2000}, {"year 2013": 2750}];

And it seems I need to this kind of map,reduce approach for large data(array sets), is there any other library or practices I can do to make the code solid?

Thanks in advance.

like image 427
arnold Avatar asked Nov 30 '22 13:11

arnold


1 Answers

Given a slightly different structure of data:

var data = [{
  "date": "2011-12-02T00:00",
  "value": 1000
}, {
  "date": "2013-03-02T00:00",
  "value": 1000
}, {
  "date": "2013-03-02T00:00",
  "value": 500
}, {
  "date": "2012-12-02T00:00",
  "value": 200
}, {
  "date": "2013-04-02T00:00",
  "value": 200
}, {
  "date": "2013-04-02T00:00",
  "value": 500
}, {
  "date": "2013-03-02T00:00",
  "value": 500
}, {
  "date": "2013-04-12T00:00",
  "value": 1000
}, {
  "date": "2012-11-02T00:00",
  "value": 600
}];

You could use underscore:

var grouped = _.groupBy(data, function(item) {
    return item.date;
});

var groupedByYear = _.groupBy(data, function(item) {
    return item.date.substring(0,4);
});

var groupedByMonth = _.groupBy(data, function(item) {
    return item.date.substring(0,7);
});

console.log(groupedByYear);

See related answer: Javascript - underscorejs map reduce groupby based on date

like image 110
burin Avatar answered Dec 05 '22 14:12

burin