javascript - 在排序数组中查找/跟踪元素

标签 javascript arrays sorting search

假设有一个像 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 将是对排序数组中的对象的引用。

关于javascript - 在排序数组中查找/跟踪元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031145/

相关文章:

python - 按索引和列排序

algorithm - 使用哪种多标准排序算法?

javascript - 在Processing 3.0中使用缓动鼠标进行绘图

javascript - Google DFP - 从内部调整 SafeFrame 自定义广告素材外部 Iframe 容器的大小(展开广告)

javascript - 如何将用户ID从浏览器传递到 Protractor ?

java - 嵌套 For 循环终止后递增

arrays - 我想在matlab中将char矩阵转换成数字

javascript - 选择具有相同类的多个div

python - numpy 用数组填充数组

C语言比较链表中的chararrays