简体   繁体   中英

find/trace element in a sorted array

Let's say there is an array like var arr = [{id:'anId', value: 'aValue'}, ......] and a custom sorting by value is done to it:

arr.sort(function(){
   // sorting.....
}); 

Is there a way to trace an element during sorting?

If not is there an efficient search implementation of finding it by id without iterating and checking on each item?

Appreciate your kind help.

Since you are already applying a sorting method, which will iterate through all the elements, you can get the best performance by checking for your target ID during the sort iterations:

var prevPos = // here goes the current index of the object in the array
var item;
arr.sort(function(a,b){
    if(a.id == 'mySearchID'){
        console.log('found it, better store it')
        item = a;
        f(a.value < b.value) prevPos++ // item moved, change current pos
    }else if(b.id == 'mySearchID'){
         console.log('found it, better store it')
         item = b;
         if(a.value < b.value) prevPos-- // item moved, change current pos
    }
    //your sorting method
    return a.value < b.value
}); 
console.log(item, prevPos) //gets item obj and its new position in the array

Note that item may be updated multiple times depending on how many times your desired object is moved during the sort, but by the end of the sort item will be a reference to your object in the sorted array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM