gpt4 book ai didi

javascript - 使用 LoDash 对时间序列数据进行分组和求和

转载 作者:行者123 更新时间:2023-11-30 14:43:55 31 4
gpt4 key购买 nike

我想按 ISO 周对这些数据进行分组并汇总注册。我如何使用 LoDash 做到这一点?我最新的解决方案和示例数据如下所示:

const registrationJson = [ 
{ date: 2018-02-19T00:00:00.000Z, registrations: '7' },
{ date: 2018-02-20T00:00:00.000Z, registrations: '1' },
{ date: 2018-02-21T00:00:00.000Z, registrations: '3' },
{ date: 2018-02-22T00:00:00.000Z, registrations: '4' },
{ date: 2018-02-23T00:00:00.000Z, registrations: '1' },
{ date: 2018-02-28T00:00:00.000Z, registrations: '3' },
{ date: 2018-03-08T00:00:00.000Z, registrations: '1' } ]

const groupedResults = _(registrationJson)
.groupBy("date")
.map(item => {
return {
date: moment(item["date"])
.startOf("isoWeek")
.toString(),
registrations: _.sumBy(item, "registrations")
}
})
.value()

然而,这会返回错误的输出:

[ { date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '7' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '1' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '3' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '4' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '1' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '3' },
{ date: 'Mon Mar 12 2018 00:00:00 GMT+0100',
registrations: '1' } ]

最佳答案

您的代码的当前版本按以下方式工作:首先按日期(而不是按周!)分组,然后使用 map 转换元素。由于每个日期在该列表中都是唯一的,因此您的分组是无用的。以相反的顺序进行:

const registrationJson = [ 
{ date: 2018-02-19T00:00:00.000Z, registrations: '7' },
{ date: 2018-02-20T00:00:00.000Z, registrations: '1' },
{ date: 2018-02-21T00:00:00.000Z, registrations: '3' },
{ date: 2018-02-22T00:00:00.000Z, registrations: '4' },
{ date: 2018-02-23T00:00:00.000Z, registrations: '1' },
{ date: 2018-02-28T00:00:00.000Z, registrations: '3' },
{ date: 2018-03-08T00:00:00.000Z, registrations: '1' } ]

const groupedResults = _(registrationJson)
.map(item => {
return {
date: moment(item["date"])
.startOf("isoWeek")
.toString(),
registrations: parseInt(item.registrations)
}
})
.groupBy("date")
.mapValues(item => {
/*
here for each isoWeek start as a key you will get
list of elements for the same week; item is an array
*/
return _.sumBy(item, 'registrations');
})
.value()

还要注意数据类型。由于您的 registrations 是一个字符串,它可能会导致连接而不是求和。

关于javascript - 使用 LoDash 对时间序列数据进行分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241285/

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