简体   繁体   English

如何检查对象数组是否包含重叠?

[英]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? 如何遍历数组并比较每个索引以查看至少一个对象间隔是否与另一个对象间隔重叠?

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 ) 添加o1 !== o2检查

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM