If I understand correctly - you want to get the intersection of pairs
const range = [
[8, 12], [17, 22]],
[[5, 11], [14, 18], [20, 23]];
and you expect the intersection would be like:
const result = [[8, 11], [17, 18], [20, 22]]
It can be done with two cycles by getting the startMax and endMin, also you can reduce complecity to O(n) using indices
Okey then, now we need to build the function to find these intersections:
function intersection(user1, user2) {
const targetUser = (user1.length >= user2.lengh ? user1 : user2);
const restUser = (targetUser == user1 ? user2 : user1);
const foundItersections = targetUser.map(tu=> {
const mwminmax = restUser.map(ru => {
const startMax = (tu[0]>=ru[0] ? tu[0] : ru[0])
const endMin =(tu[1]<=ru[1] ? tu[1] : ru[1])
if(startMax<endMin){
const retarr = [].concat(startMax,endMin)
return retarr;
}
else return;
})
const filteredmwminmax = mwminmax.filter(x=>x!==undefined)
return filteredmwminmax;
})
return foundItersections.flat();
}
console.log(intersection(
[[8, 12], [17, 22]],
[[5, 11], [14, 18], [20, 23]]
))
// [[8, 11], [17, 18], [20, 22]]
console.log(intersection(
[[9, 15], [18, 21]],
[[10, 14], [21, 22]]
))
// [[10, 14]]