javascript - 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)
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)
推荐阅读
- graphql - 在graphql(JS)中清理/拒绝包含不安全html的用户输入
- python - 将csv文件读入列表并将字符串转换为整数Python
- ios - 我需要创建什么类型的证书?
- c# - MimeMessage Get Attachment Name
- python - invalid syntax when trying to make a dictionary comprehension?
- google-app-engine - 我可以让 GCS 存储桶仅对特定人员可用(或使用密码)吗
- arrays - 在VBA中访问类对象数组中的浮点数组
- ruta - Ruta,识别模式并返回其中的一部分
- ios - iOS SpringBoard 不加载通知服务扩展
- python - 根据我的代码,多行到单行