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/

相关文章:

JavaScript:单击按钮时简单加载图像

JavaScript 推送返回一个空数组

Python:使用 lambda 键混淆进行排序

javascript - Jquery在自动完成中实现这种排序方法

javascript - 未注册的 HTML 自定义元素和已注册的 HTML 自定义元素有什么区别?

javascript - D3.js 条形图 'enter' 似乎在错误的位置绘制了新条形

javascript - simpleCart.js 更新购物车项目(如果存在)

在 C 中将数据从一个矩阵复制到另一个矩阵

python - 将 2D 数组添加到 3D 数组

c++ - 使用固定数量的整数对 vector 进行排序