gpt4 book ai didi

javascript - 下划线 : group by date while calculating total of another field

转载 作者:行者123 更新时间:2023-11-30 16:37:37 27 4
gpt4 key购买 nike

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

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

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

[{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>

关于javascript - 下划线 : group by date while calculating total of another field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com