Javascript object group by day,month,year

前端 未结 2 1060
星月不相逢
星月不相逢 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: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

提交回复
热议问题