4

我正在开发应用程序,我需要对不同的 javascript 对象集进行分组,这些对象将基于月、日和年。

一天我正在做如下

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;
    }

如何改进上述代码并将其用于月份和年份计算?我彻底了解了 underscore.js,它有一个groupBy方法。但似乎不符合我的要求。我也想按月份和年份分组,因为

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

输出应该是:

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

看来我需要这种映射,减少大数据(数组集)的方法,我可以做任何其他库或实践来使代码可靠吗?

提前致谢。

4

2 回答 2

20

给定稍微不同的数据结构:

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
}];

你可以使用下划线:

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);

查看相关答案:Javascript - underscorejs map reduce groupby based on date

于 2013-05-25T05:29:55.257 回答
2

请查看以下重构是否对您有用 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);
于 2013-05-23T10:34:17.350 回答