假设有一个像 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/