使用Moment js和Lodash按时间戳分组

问题描述

我有一个像这样的数据集:

2020-09-02 02:22:14
2020-09-05 10:22:14
2020-09-03 06:22:14
2020-09-07 04:22:14
2020-09-02 11:22:14
2020-09-09 03:22:14
2020-09-03 10:22:14
2020-09-04 06:22:14
2020-09-02 07:22:14
2020-09-02 06:22:14
2020-09-02 10:22:14

我想做的是将时间戳每两个小时分组一次,例如:

[
02:00:00: ['2020-09-02 02:22:14','2020-09-04 02:22:14'],04:00:00: ['2020-09-07 04:22:14'],06:00:00: ['2020-09-03 06:22:14','2020-09-02 06:22:14'],08:00:00: [] -- Empty array when no timestamp falls in that given range
10:00:00: [etc..] --up until 00:00:00
]

我尝试过的事情:

    const hello = _.groupBy(something,(date) => {
      const timeStamp = moment(date).add(30,'minutes').startOf('hour').format('HH:mm:ss');
      return moment('1960-02-02 ' + timeStamp).format('YYYY-MM-DD HH:mm:ss');
    });

哪个返回以下内容

2020-09-12 02:00:00: (2) ["2020-09-02 02:22:14","2020-09-02 02:22:14"]
2020-09-12 03:00:00: ["2020-09-09 03:22:14"]
2020-09-12 04:00:00: ["2020-09-07 04:22:14"]
2020-09-12 06:00:00: (3) ["2020-09-03 06:22:14","2020-09-04 06:22:14","2020-09-02 06:22:14"]
2020-09-12 07:00:00: ["2020-09-02 07:22:14"]
2020-09-12 10:00:00: (3) ["2020-09-05 10:22:14","2020-09-03 10:22:14","2020-09-02 10:22:14"]
2020-09-12 11:00:00: ["2020-09-02 11:22:14"]

这不是我想要的,我试图浏览其他一些帖子以得到一个主意,但是任何帮助都将不胜感激。

解决方法

您可以初始化两个小时范围的数组并将数据分组到该范围内

const data = [
  "2020-09-02 02:22:14","2020-09-05 10:22:14","2020-09-03 06:22:14","2020-09-07 04:22:14","2020-09-02 11:22:14","2020-09-09 03:22:14","2020-09-03 10:22:14","2020-09-04 06:22:14","2020-09-02 07:22:14","2020-09-02 06:22:14","2020-09-02 10:22:14",]

const byTwoHours = Array(12)
  .fill(0)
  .map((_,index) => `${String(index * 2).padStart(2,"0")}:00:00`)

const byTwoHoursLookup = byTwoHours.reduce(
  (acc,range) => ({ ...acc,[range]: [] }),{}
)

data.forEach((date) => {
  const hour = moment(date,"YYYY-MM-DD HH:mm:ss").format("HH:00:00")
  for (let i = byTwoHours.length - 1; i >= 0; i--) {
    if (hour >= byTwoHours[i]) {
      byTwoHoursLookup[byTwoHours[i]].push(date)
      break
    }
  }
})

console.log(byTwoHoursLookup)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

,

为什么不使用香草JS?

像这样吗?

em