javascript underscorejs组和总和数据

时间:2014-08-11 07:47:02

标签: javascript group-by underscore.js

我有这样的数据:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100},
    {date: "2010-02-09", total: 300}
];

我想像这样创建一个分组和总和。

var grouped = [
    {date: "2000", total: 220}, 
    {date: "2010", total: 100}
];

我使用的是underscorejs,但没有找到功能。

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();

    return {date: year, total: item.total}; 
});

workig代码为here

2 个答案:

答案 0 :(得分:1)

我相信您正在寻找reduce功能:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100}
];

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();        
    return {date: year, total: item.total}; 
});

var grouped = _.reduce(byYear, function(memo, item) {
    memo[item.date] = (memo[item.date] || 0) + item.total;
    return memo;
}, {});

答案 1 :(得分:1)

使用reduce功能。在我发帖之前,我看到这已被jst回答。但只花时间编码。所以无论如何都在这里张贴。顺便说一句,这个答案使用链接。

var byYear = _.chain(dates)
            .map(function(item){ 
                var year = new Date(Date.parse(item.date)).getFullYear();
                return {date: year, total: item.total}; 
            })
            .groupBy('date')
            .map(function (value,key) { 
                            var reduceVal = _.reduce(value, function (acc, val)
                                                            { 
                                                                return acc + val.total;
                                                            },0 ); 
                            return {'year':key,'total' :reduceVal};
                })
            .value();


alert(JSON.stringify(byYear));