我有两个间隔一定的数组:
[
[
[8:00, 11:30], // [begin,end]
[12:00, 16:00], // [begin,end]
[18:00, 21:00] // [begin,end]
],
[
[8:00, 15:30], // [begin,end]
[16:00, 17:45], // [begin,end]
[19:00, 21:30] // [begin,end]
]
]
我需要找到这些时间的通用间隔,所以应该是:
[
[8:00, 11:30],
[12:00, 15:30],
[19:00, 21:00]
]
我将小时数更改为分钟数,然后将第一个数组中的间隔与第二个数组中的间隔进行了比较,但输出结果并不像上面所示。
有人知道如何解决吗?
let hours = [[[8:00,11:30],[12:00,16:00],[18:00,21:00]]
[[8:00,15:30],[16:00,17:45],[19:00,21:30]]]
let commonHors=[];
for (let i=0; i<(hours||[]).length; i++){
for(let j=0; j<(hours||[])[i].length; j++){
let fromFirst = moment.duration(hours[0][j][0]).minutes() +
moment.duration(hours[0][j][0]).hours()*60;
let fromSec = moment.duration(hours[1][j][0]).minutes() +
moment.duration(hours[1][j][0]).hours()*60;
let toFirst = moment.duration(hours[0][j][1]).minutes() +
moment.duration(hours[0][j][1]).hours()*60;
let toSec = moment.duration(hours[1][j][1]).minutes() +
moment.duration(hours[0][j][1]).hours()*60;
if(fromFirst >= fromSec && toFirst <= toSec){
commonHors.push(hours[0][j][0],hours[0][j][1]);
}
else if(fromFirst <= fromSec && toFirst <= toSec){
commonHors.push(hours[1][j][0],hours[0][j][1]);
}
else if(fromFirst >= fromSec && toFirst >= toSec){
commonHors.push(hours[0][j][0],hours[1][j][1]);
}
else if(fromFirst <= fromSec && toFirst >= toSec){
commonHors.push(hours[1][j][0],hours[1][j][1]);
}
}
}
答案 0 :(得分:1)
到目前为止,这并不是最漂亮的解决方案,但是它在输入数据有效且已经排序的情况下起作用。希望我了解您的问题,并且我的解决方案会有所帮助。编辑:我使用字符串而不是其他时间格式-刚刚意识到,但由于我按数值排序,因此更改它应该不难;
let intervals = [
[
['8:00', '11:30'],
['12:00', '16:00'],
['18:00', '21:00']
],
[
['8:00', '15:30'],
['16:00', '17:45'],
['19:00', '21:30']
]
];
let out = [];
while(intervals[0].length > 0) {
let laterNum = later(0, 0);
let startTime = intervals[laterNum][0][0];
let earlyNum = earlier(0, 1);
let endTime = intervals[earlyNum][0][1];
if (Number(endTime.replace(':', '')) > Number(startTime.replace(':', '')))
out.push([startTime, endTime]);
intervals[earlyNum].splice(0, 1);
}
function earlier(line, time) {
let a = intervals[0][line][time];
let b = intervals[1][line][time];
return Number(a.replace(':', '')) < Number(b.replace(':', '')) ? 0 : 1;
}
function later(line, time) {
return earlier(line, time) === 1 ? 0 : 1;
}
console.log(out);