javascript - 使用 Moment 按天合并每小时日期列表

标签 javascript datetime momentjs lodash

我的价格/日期数据的形式为[日期,价格]

let priceData = [
    [1551052800000, 0.33739737955243454]
    [1551139200000, 0.33628886196814234]
    [1551225600000, 0.12674156277665535]
    [1551312000000, 0.16847247989576378]
    [1557792000000, 0.5650889670671049]
    [1557878400000, 0.6003006017008962]
    [1557964800000, 0.6438789432408669]
    [1558051200000, 0.6684895789112406]
]

我想知道一种干净的方法来使用 lodash 或 map 或其他东西获取这样的列表,并根据相同的日期将其组合起来,例如......

// the data below may not be accurate, the point here is the structure
let exampleChuckedData = [
    [
            [1551052800000, 0.33739737955243454]
            [1551139200000, 0.33628886196814234]
            [1551225600000, 0.12674156277665535]
            [1551312000000, 0.16847247989576378]
    ]
    [
            [1557792000000, 0.5650889670671049]
            [1557878400000, 0.6003006017008962]
            [1557964800000, 0.6438789432408669]
            [1558051200000, 0.6684895789112406]
    ]
]

// Or more conceptually
// Grouped by same date
let exampleConceptData = [
    [
            ['01/01/2019', 0.33739737955243454]
            ['01/01/2019', 0.33628886196814234]
            ['01/01/2019', 0.12674156277665535]
            ['01/01/2019', 0.16847247989576378]
    ]
    [
            ['01/02/2019', 0.5650889670671049]
            ['01/02/2019', 0.6003006017008962]
            ['01/02/2019', 0.6438789432408669]
            ['01/02/2019', 0.6684895789112406]
    ]
]

我使用 moment 来满足我所有的日期格式化需求。也许有一种方法可以集成 moment 来帮助解决这个问题,就像他们的 *.isSame()

最佳答案

您可以使用_.groupBy(),并在回调中使用moment(date).day()将每个日期转换为一天。使用 _.values() 将组的对象转换为数组:

const priceData = [[1551052800000,0.33739737955243454],[1551139200000,0.33628886196814234],[1551225600000,0.12674156277665535],[1551312000000,0.16847247989576378],[1557792000000,0.5650889670671049],[1557878400000,0.6003006017008962],[1557964800000,0.6438789432408669],[1558051200000,0.6684895789112406]]

const result = _.values(_.groupBy(priceData, ([d]) => moment(d).startOf('day')
))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>

关于javascript - 使用 Moment 按天合并每小时日期列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57030509/

相关文章:

javascript - 使用模块作为单例

c# - 在服务器 2008 上将字符串转换为日期时间

c# - 检查夏令时是否有效?

r - 如何在 POSIX 中提取小时、分钟和秒(忽略日期)

未使用 Moment.js 定义 Javascript 函数

javascript - 使用 Workbox 缓存整页

javascript - IE7 : Can't display popup box when hovering over transparent background

javascript - Moment.js : Determine whether or not 24 hours has passed or not

javascript - Moment js - 在不考虑时区的情况下获取日期

javascript - 如何在禁用时更改按钮的颜色然后在启用时返回