我需要过滤掉以下对象数组的开始和结束(moment.js)时间的任何重叠
[{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")},
{ start: moment("2019-03-23T14:40:00.000"), end: moment("2019-03-23T17:30:00.000")},
{ start: moment("2019-03-23T18:45:00.000"), end: moment("2019-03-23T19:45:00.000")},
{ start: moment("2019-03-23T17:10:00.000"), end: moment("2019-03-23T20:00:00.000")},
{ start: moment("2019-03-23T21:35:00.000"), end: moment("2019-03-23T22:35:00.000")},
{ start: moment("2019-03-23T19:15:00.000"), end: moment("2019-03-23T22:05:00.000")},
{ start: moment("2019-03-23T22:30:00.000"), end: moment("2019-03-23T23:30:00.000"),
}]
在上面的示例中,日期都在同一天 (03/23),因此在查看时间时,我需要遍历每个对象并获取最早的开始时间和最晚的结束时间,没有重叠。我需要一个最终的交替 start、end、start、end ...
时间数组。
因此,对于上面的示例,我需要过滤到以下内容:
start: 14:40:00
end: 17:30:00
start: 18:45:00
end: 20:00:00
start: 21:35:00
end: 23:30:00
如您所见,第二个开始时间仅出现在第一个结束时间之后,最后的结束时间基本上是最后一个可用的结束时间。整个集合中最早可用的开始时间是 14:40:00,因此它获得第一个插槽。
再如开始时间17:10:00;这个开始时间已经被第一个开始/结束时间覆盖,所以它被忽略了,但是它的配对结束时间 20:00:00 是在 19:45:00 之后,所以它取代了循环中的那个结束时间。
我希望这是有道理的,如果没有,请告诉我。
我的想法仍然包含重叠,即使它有效我也不满意。
times.forEach(time => {
// start with the first object
if (filtered.length === 0) {
filtered.push({'start': time.start, 'end': time.end});
}
// if this start time is AFTER the prior end time, add it
if (time.start.isAfter(filtered[filtered.length-1]['end'])) {
filtered.push({'start': time.start, 'end': time.end});
}
if (time.start.isBefore(filtered[filtered.length-1]['end'])) {
// replace the prior end time
filtered[filtered.length-1]['end'] = time.end;
}
});
正如我所说,显然这不是很好,但不确定如何最好地完成。
最佳答案
boundaries = [];
times.forEach (time => {
boundaries.push ({type: "start", value: time.start});
boundaries.push ({type: "end", value: time.end})
});
这将为您提供一组如下所示的边界:
[
{type: "start", value: moment("2019-03-23T15:55:00.000")},
{type: "end", value: moment("2019-03-23T16:55:00.000")},
{type: "start", value: moment("2019-03-23T14:40:00.000")},
{type: "end", value: moment("2019-03-23T17:30:00.000")},
{type: "start", value: moment("2019-03-23T18:45:00.000")},
{type: "end", value: moment("2019-03-23T19:45:00.000")},
{type: "start", value: moment("2019-03-23T17:10:00.000")},
{type: "end", value: moment("2019-03-23T20:00:00.000")},
{type: "start", value: moment("2019-03-23T21:35:00.000")},
{type: "end", value: moment("2019-03-23T22:35:00.000")},
{type: "start", value: moment("2019-03-23T19:15:00.000")},
{type: "end", value: moment("2019-03-23T22:05:00.000")},
{type: "start", value: moment("2019-03-23T22:30:00.000")},
{type: "end", value: moment("2019-03-23T23:30:00.000")}
]
现在按值
对这个数组进行排序并迭代排序后的数组,计算您通过的“开始”边界减去您通过的“结束”边界的数量。 IE。在每个“开始”边界递增计数器,并在每个“结束”边界递减计数器。
每次计数器从零变为非零时,输出过滤的“开始”边界。每次计数器从非零下降到零时,输出过滤的“结束”边界。
关于javascript - 过滤对象日期时间的javascript数组,这样就没有重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300403/