Javascript object group by day,month,year

前端 未结 2 1049
星月不相逢
星月不相逢 2021-01-06 15:06

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

相关标签:
2条回答
  • 2021-01-06 15:30

    Please see if the following refactor is useful for you http://jsfiddle.net/wkUJC/

    var dates = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
    
    function calc(dates) {
        var response = {};
        dates.forEach(function(d){
            for (var k in d) {
                var _ = k.split("-");
                var year = _[0]
                var month = _[1]
                if (!response[year]) response[year] = {total: 0}
                response[year][month] = response[year][month] ? response[year][month]+d[k] : d[k]
                response[year].total+= d[k]
            }
        });
        console.log(response);
        return response;
    }
    
    calc(dates);
    
    0 讨论(0)
  • 2021-01-06 15:32

    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

    0 讨论(0)
提交回复
热议问题