Search code examples
javascriptarraysmutual-exclusion

Search values in array of objects js


I need to push my new object in array of objects and check: if new object doesnt overlap objects that exists by start and end values. I write this one. Can i make it shorter? Or maybe there is better method to do it?

let arr = [
    {
        start: 0,
        end: 10
    },
    {
        start: 30,
        end: 40
    },
    {
        start: 60,
        end: 70
    },
    {
        start: 100,
        end: 110
    },
    {
        start: 140,
        end: 150
    },
    {
        start: 180,
        end: 190
    }
];

let objToPush = {
    start: 45,
    end: 50
}

if (!arr.find(o => objToPush.start > o.start && objToPush.start < o.end)) {
    if (!arr.find(o => objToPush.end > o.start && objToPush.end < o.end)) {
        console.log('push');
        arr.push(objToPush);
    } else {
        console.log('not push');
    }
} else {
    console.log('not push');
}

Solution

  • Ashish hit the nail on the head, and that overlap comparison is awesome!

    For anyone who needs it fast:

    const overlaps = (obj1, obj2) => (
      obj1.start < obj2.end && obj1.end > obj2.start
    );
    
    const overlapExists = (arr, newObj) => (
      arr.some(obj => overlaps(obj, newObj))
    );
    

    This is assuming that:

    1. All objects have a start value that's less than or equal to their end value.
    2. Equal values shouldn't count as overlapping.