gpt4 book ai didi

javascript - 使用 groupBy 对数组进行分组

转载 作者:行者123 更新时间:2023-11-28 05:03:21 41 4
gpt4 key购买 nike

我使用此函数对数组进行分组:

Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}

我在另一个获取日期的函数中使用它

    vm.parkings.forEach(function(value, key) {
value.receiptsByDate = [];
if (value.receipts != undefined) {
value.receipts.forEach(function(rcpts) {
var date = rcpts.date.split('/');
var newDate = date[2] + '/' + date[0];
var year = date[2];
var month = date[0];
var price = rcpts.value;
value.receiptsByDate.push({newDate, price, month, year});
value.newReceipt = value.receiptsByDate.groupBy('month');
})
}
})

结果:

Result

在我的新收据中,我将对象按月份排序,好吧。

我想根据月份汇总价格。示例:在数组三内,访问对象并对价格求和。

这是最好的方法吗?

编辑

我使用了下划线并且它有效。它看起来像这样:

var result = _.groupBy(receiptsByDate, "month");
var out = _(result).map(function(g, key) {
return {month: key, price: _(g).reduce(function(m, x){return m + x.price}, 0)}
})

最佳答案

尝试linq.js图书馆:

var res = Enumerable.From([
{date: new Date(), price: 10},
{date: new Date(), price: 20},
{date: new Date(2014, 15, 4), price: 30},
{date: new Date(2014, 15, 4), price: 40},
{date: new Date(2014, 15, 4), price: 50}
]).GroupBy("$.date.getMonth() + 1", null, function (key, gr) {
var temp = {
month: key,
totalPrice: gr.Sum("$.price")
};
console.log(temp);
return temp;
}).ToArray();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://neue.cc/linq.min.js"></script>

关于javascript - 使用 groupBy 对数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967987/

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