Search code examples
javascriptalgorithmbinary-search

Efficient search in a array of obj in Javascript


let's say i've a preordered array of object such as this one:

let data = [
    { moment: '00:01', otherProp: 'something', somethingMore: 'someelse'},
    { moment: '01:10', otherProp: 'something', somethingMore: 'someelse'},
    { moment: '05:37', otherProp: 'something', somethingMore: 'someelse'},
    { moment: '07:51', otherProp: 'something', somethingMore: 'someelse'},
    //and so on
]

I've got in input x which is formatted as an hour:minutes string (ex. x='06:05') and i need to find the two consecutive objects (data[i] and data[i+1]) such that data[i].moment <= x < data[i+1].moment

Suppose the array has almost 200 elements and i need to fastest way to find the results. Do i've to implement the binary search from scratch? is there a library i can use?


Solution

  • Do i've to implement the binary search from scratch?

    what's the point? it's just a few lines of code:

    let data = [
        { moment: '00:01', otherProp: 'something', somethingMore: 'someelse'},
        { moment: '01:10', otherProp: 'something', somethingMore: 'someelse'},
        { moment: '05:37', otherProp: 'something', somethingMore: 'someelse'},
        { moment: '07:51', otherProp: 'something', somethingMore: 'someelse'},
        //and so on
    ];
    let search = '06:05';
    
    let lo = -1, hi = data.length-1, mid;
    while(hi > lo){
      if(data[mid=(lo+hi+1)>>1].moment > search) {
        hi = mid-1;
      } else {
        lo = mid;
      }
    }
    
    console.log(data[lo]);
    console.log(search);
    console.log(data[lo+1]);
    .as-console-wrapper{top:0;max-height:100%!important}