下划线:按日期分组,同时计算另一个字段的总数

underscore: group by date while calculating total of another field

我有一个具有以下结构的对象数组:

[{date: 08/17/15, total: 20}, {date: 08/17/15, total: 10}, {date: 08/15/15, total: 15}, {date: 08/14/15, total: 20}]

并且我想按天对对象进行分组,同时对当天每个对象的 "total" 字段求和。所以对于上面的数组,我想要这样的结果:

[{date: 08/17/15, total: 30}, {date: 08/15/15, total: 15}, {date: 08/14/15, total: 20}]

目前,我正在尝试使用下划线对日期进行分组,方法如下:

var groupedDates = _.groupBy(groupedValues, 'date', function(d) {
    return {
        date: d.date,
        total: d.total
    };
});

但我无法计算总数以进行加总。有帮助吗?

你可以借助 reduce 和 find 方法以非常简洁的方式解决它:

var data = [{date: '08/17/15', total: 20}, {date: '08/17/15', total: 10}, {date: '08/15/15', total: 15}, {date: '08/14/15', total: 20}];

var result = _.reduce(data, function(prev, curr) {
    var found = _.find(prev, function(el) { return el.date === curr.date; });
    found ? (found.total += curr.total) : prev.push(_.clone(curr));
    return prev;
}, []);

alert(JSON.stringify(result, null, 4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>