find/trace 排序数组中的元素

find/trace element in a sorted array

假设有一个像 var arr = [{id:'anId', value: 'aValue'}, ......] 这样的数组,并且按 value 对其进行了自定义排序:

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

有没有办法在排序过程中跟踪元素?

如果没有,是否有通过 id 找到它而无需迭代和检查每个项目的高效搜索实现?

感谢您的帮助。

由于您已经在应用排序方法,它将遍历所有元素,因此您可以通过在排序迭代期间检查目标 ID 来获得最佳性能:

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

请注意,item 可能会更新多次,具体取决于您想要的对象在排序过程中移动了多少次,但在排序结束时 item 将成为对您对象的引用在排序数组中。