Search values in array of objects js

104 views Asked by At

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');
}
3

There are 3 answers

0
Zevgon On BEST ANSWER

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.
0
ashish singh On

plus please check that your logic will not work for existing point (10,20) and point to insert (0, 30)

yes it can be improved

first of all basic improvement

those two if statements can be combined to one

if( *full condition *) //push

second improvement

extract that full condition to a function

function overlaps(obj1, obj2) {
  // check overlap
}

then use overlaps function for find function's predicate it will be more readable

one more improvement: you can make that condition for overlap easier

let for simplicity two points being compared be (a,b) and (c,d)
// a,b are start and end of first object and c,d for second
assuming a <= b and c <= d

condition for overlap of two points is

a < d && b > c

this is what your overlaps function can use

please try to write code for this one and check if it doesnt work

0
Jonas Wilms On

If end is smaller than the existing end, start will be too. The same applies the other way round, so we actually just need one condition:

if (!arr.find(o => 
 !( objToPush.end < o.start ||
    objToPush.start > o.end )
)) arr.push(objToPush);

We can extract that into a function and return false if it fails:

const add = objToPush => !arr.find(o => 
 !( objToPush.end < o.start ||
    objToPush.start > o.end )
)) && arr.push(objToPush);

console.log(add({start:5,end:15}));

In action