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

Group by timestamps with Moment js and 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');
    });

其中returns以下:

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"]

这不是我想要的,我试图浏览其他一些帖子来了解一个想法,但如果有任何帮助,我们将不胜感激。

为什么不使用 vanilla JS?

是这样的吗?

const pad = num => ("0"+num).slice(-2);
const times = `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`.split("\n");

const hours = Array.from(Array(24).keys()).map(i => pad(++i)).filter(item => item%2===0)
//hours.push("00");// better change at the end
const schedule = hours.reduce((acc, hh) => {
  acc[`${hh}:00:00`] = times.filter(t => {
    const thh = t.match(/ (\d{2}):/)[1]*1
    const period = [+hh,+hh+2];
    return thh >= period[0] && thh < period[1];
  })
  return acc;
},{})
 console.log(schedule)

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

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>