Ad
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?
Ad
Answer
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}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad