Home > Blockchain >  How to check the JavaScript array objects are overlapping
How to check the JavaScript array objects are overlapping

Time:03-25

I have an array of objects containing start and end range.

var ranges = [{
    start: 1,
    end: 5
}]

I want to push an object like this without overlapping with the previous start and end range

{
    start: 6,
    end: 10
}

How to check new object overlapping with the existing objects

Edit:

  {
        start: 50,
        end: 100
    },
{
        start: 11,
        end: 49
}

CodePudding user response:

Got the answer thanks everyone for your response.

let isValid = timeRanges.every(r => (r.begin != selected.begin && r.begin < selected.begin &&  selected.begin > r.end) && (r.end != selected.end && r.end < selected.begin &&  selected.end > r.end));

CodePudding user response:

You can try this :

const ranges = [{
  start: 1,
  end: 5
}];

const rangeObj = {
  start: 6,
  end: 10
};

function checkRangeOverlap(obj) {
  let res = ''
  ranges.forEach((obj) => {
    res = (obj.end > rangeObj.start) ? 'Overlaping': 'No Overlap';
  });
  return res;
}

console.log(checkRangeOverlap(rangeObj));

  • Related