我有以下时间间隔的开始时间和结束时间:
{ status: 'A', start: 12:20, end: 12:35},
{ status: 'B', start: 12:21, end: 12:28},
{ status: 'C', start: 12:22, end: 12:30},
{ status: 'D', start: 12:30, end: 12:45},
{ status: 'E', start: 12:40, end: 12:48}
正如您所看到的,有一些重叠,例如:12:22 -->12:28
包含A, B, and C
个状态。或D and E
重叠12:40 -->12:45
。所有数据都根据其开始时间排序。如何在Javascript中编写程序以获得重叠及其对应的状态?
基本上,输出如下:
[A, B, C] : {12:22 , 12:28}
[D, E] : {12:40 , 12:45}
...
当前代码找到两个重叠:
const schedule = [
{ status: 'A', start: '12:20', end: '12:35'},
{ status: 'B', start: '12:21', end: '12:28'},
{ status: 'C', start: '12:22', end: '12:30'},
{ status: 'D', start: '12:30', end: '12:45'},
{ status: 'E', start: '12:40', end: '12:48'}
]
const intervali = {start: '', end:'', status:''};
for (i = 0; i < schedule.length - 1; i++) {
interval_i = schedule[i];
for (j = i + 1; j < schedule.length; j++) {
interval_j = schedule[j];
if (interval_j.start < interval_i.end && interval_j.end > interval_i.start) {
intervali['start'] = interval_i.start > interval_j.start ? interval_i.start : interval_j.start;
intervali['end'] = interval_i.end < interval_j.end ? interval_i.end : interval_j.end;
intervali['status'] = interval_i.status + ' - ' + interval_j.status;
console.log(intervali)
}
}
}
答案 0 :(得分:0)
您可以使用嵌套循环遍历每个项目两次并运行比较。请参阅下面的评论。
const schedule = [
{ status: 'A', start: '12:20', end: '12:35'},
{ status: 'B', start: '12:21', end: '12:28'},
{ status: 'C', start: '12:22', end: '12:30'},
{ status: 'D', start: '12:30', end: '12:45'},
{ status: 'E', start: '12:40', end: '12:48'}
]
// convert a time string to integer of minutes
const toMinutes = time => {
const [hour, minute] = time.split(':')
return (Number(hour) * 60) + Number(minute)
}
function findOverlappying(schedule) {
const l = schedule.length
const ret = {}
// loop over each item twice
for (let i = 0; i < l; i++) {
for (let j = 0; j < l; j++) {
const left = schedule[j]
const right = schedule[i]
// set the status to the return object
ret[left.status] = ret[left.status] || {
...left,
overlap: []
}
// don't process for the same key
if (i === j) {
continue
}
// get the start and stop times as minutes to compare
const leftStart = toMinutes(left.start)
const leftStop = toMinutes(left.end)
const rightStart = toMinutes(right.start)
const rightStop = toMinutes(right.end)
// compare the start and stop times for overlapping
if (
(leftStart > rightStart && leftStart < rightStop) ||
(leftStop > rightStart && leftStop < rightStop)
) {
// add time to overlapping status identifier
ret[left.status].overlap.push(right.status)
}
}
}
return ret
}
console.log(
findOverlappying(schedule)
)
&#13;
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
&#13;