首页 > 解决方案 > How to check if an array of object contains an overlap?

问题描述

Suppose I have the following array:

[
 {start: "0", end: "3"}, 
 {start: "4", end: "6"},
 {start: "2", end: "8"}
]

as you can see the third object overlap the first two interval. For this purpose I created the following function:

checkOverlap = function(o1, o2){
  return ((o1.end - o2.start) >= 0 && (o2.end - o1.start) >= 0) ? true : false;
}

I wrote this code:

for (var i = 0; i < array.length; i++) 
{
   for(var x = 0; x < array.length; x++){
      if(this.checkOverlap(array[i], array[x])){
         throw new Error("overlap detected");
      }
   }
}

but this will generate an error also when there are no overlap

how can I iterate over the array and compare each index to see if at least one object interval overlap another object interval?

标签: javascript

解决方案


The problem with your code is that you are checking each item with its self as well.

If you exclude that it should work. (add a o1 !== o2 check)

const array = [
 {start: "0", end: "3"}, 
 {start: "4", end: "6"},
 {start: "2", end: "8"}
]

checkOverlap = function(o1, o2){
  return o1 !== o2 && ((o1.end - o2.start) >= 0 && (o2.end - o1.start) >= 0) ? true : false;
}

for (var i = 0; i < array.length; i++) 
{
   for(var x = 0; x < array.length; x++){
      if(this.checkOverlap(array[i], array[x])){
         throw new Error("overlap detected");
      }
   }
}


Here is another approach just for the syntactic sugar of it

const ranges = [
 {start: "0", end: "3"}, 
 {start: "4", end: "6"},
 {start: "5", end: "8"}
];

const overlapCheck = (A,index,arr) => arr.some(B=>A!==B && (A.start < B.end && A.end > B.start))

const isOverlap = ranges.some(overlapCheck)

console.log(isOverlap)


推荐阅读