Javascript 在对象数组中,查找属性与搜索匹配的对象索引的最快方法

Javascript 在对象数组中,查找属性与搜索匹配的对象索引的最快方法,javascript,arrays,indexof,Javascript,Arrays,Indexof,我一直在网上冲浪,试图找到一个有效的方法来做到这一点,但却一无所获。我有一个如下所示的对象数组: array[i].id = some number; array[i].name = some name; 我想做的是找到id等于0,1,2,3或4中的一个的对象的索引。 我想我可以这样做: var indexes = []; for(i=0; i<array.length; i++) { (array[i].id === 0) ? { indexes[0] = i } (array

我一直在网上冲浪,试图找到一个有效的方法来做到这一点,但却一无所获。我有一个如下所示的对象数组:

array[i].id = some number;
array[i].name = some name;
我想做的是找到id等于0,1,2,3或4中的一个的对象的索引。 我想我可以这样做:

var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}
例如,返回undefined,这可能是它应该返回的。 提前谢谢

var指数=[];
var indices = [];
var IDs = [0, 1, 2, 3, 4];

for(var i = 0, len = array.length; i < len; i++) {
    for(var j = 0; j < IDs.length; j++) {
        if(array[i].id == ID) indices.push(i);
    }
}
var id=[0,1,2,3,4]; 对于(变量i=0,len=array.length;i
听起来,您可以创建一个简单的迭代器,并使用回调函数进行测试。像这样:

function findElements(array, predicate)
{
    var matchingIndices = [];

    for(var j = 0; j < array.length; j++)
    {
        if(predicate(array[j]))
           matchingIndices.push(j);
    }

    return matchingIndices;
}
新的数组方法适用于以下情况:

var filteredArray = array.filter(function (element) { 
    return element.id === 0;
});
jQuery也可以通过


编辑:值得一提的是,这两个函数只是在引擎盖下迭代,它们与滚动您自己的过滤函数之间不会有明显的性能差异,但为什么要重新发明轮子。

也许您希望使用更高阶的函数,如“map”。 假设您希望按“字段”属性进行搜索:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

结果是一个id的查找列表。使用给定的id,我们可以得到记录的索引。

修改Tejs对mongoDB和Robomongo的回答,我更改了

matchingIndices.push(j);


在数组中查找元素索引的最简单方法

ES5语法:
[{id:1},{id:2},{id:3},{id:4}].findIndex(函数(obj){return obj.id==3})


ES6语法:
[{id:1},{id:2},{id:3},{id:4}].findIndex(obj=>obj.id==3)

由于我还不能发表评论,我想显示基于Umair Ahmed posted方法使用的解决方案,但当您想搜索键而不是值时:

[{"a":true}, {"f":true}, {"g":false}]
.findIndex(function(element){return Object.keys(element)[0] == "g"});

我知道它没有回答扩展的问题,但标题没有指定每个对象想要什么,因此我想谦虚地分享这一点,以避免将来让其他人头疼,而我认为它可能不是最快的解决方案。

使用ES6
映射功能:

let idToFind = 3;
let index = someArray.map(obj => obj.id).indexOf(idToFind);

由于使用常规数组查找时没有答案

var one = {id: 1, name: 'one'};
var two = {id: 2, name:'two'}
var arr = [one, two] 

var found = arr.find((a) => a.id === 2)

found === two // true

arr.indexOf(found) // 1

总结上面所有的好答案和我关于查找一些评论中出现的所有索引的补充答案

  • 返回第一次出现的索引
  • const数组=[{id:1},{id:2},{id:3},{id:4},{id:2}];
    const-IdyourareLooking=2;
    //ES5
    //产出:1
    map(函数(x){return x.id;}).indexOf(idiourelooking);
    //ES6
    //产出:1
    
    array.findIndex(obj=>obj.id==idyourareLooking)我创建了一个名为的小型实用程序,您可以通过一个具有O(1)复杂性的唯一标识符访问数组中的项。例如:

    const SuperArray = require('super-array');
    
    const myArray = new SuperArray([
      {id: 'ab1', name: 'John'},
      {id: 'ab2', name: 'Peter'},
    ]);
    
    console.log(myArray.get('ab1')); // {id: 'ab1', name: 'John'}
    console.log(myArray.get('ab2')); // {id: 'ab2', name: 'Peter'}
    
    将返回索引1(仅适用于ES 2016)

    使用ES6的新方法

    let picked_element = array.filter(element => element.id === 0);
    

    const index=array.findIndex(item=>item.id==='your id')

    这将获得id==您id的数组中项的索引

    array=[{id:1},{id:2}];
    const index=array.findIndex(item=>item.id==2);
    
    控制台日志(索引)如果您关心性能,请不要使用查找筛选映射或上述任何方法

    下面是一个演示最快方法的示例。是指向实际测试的链接

    设置块

    var items = []
    
    for(var i = 0; i < 1000; i++) {
        items.push({id: i + 1})
    }
    
    var find = 523
    
    最慢的方法

    var index = -1
    for(var i = 0; i < items.length; i++) {
        if(items[i].id === find) {
            index = i;
            break;
        }
    }
    
    items.map(item => item.id).indexOf(find);
    

    我喜欢这种方法,因为它很容易与对象中的任何值进行比较,无论嵌套有多深

     while(i<myArray.length && myArray[i].data.value!==value){
      i++; 
    }
    // i now hows the index value for the match. 
     console.log("Index ->",i );
    

    while(i一种基于特定匹配查找数组中对象索引的简单方法

    //list of bookings
    const bookings = [
        { status: "accepted", _id: "6055cadd062eb5153c089121", title: "This is test title", user: "id", team: "id" },
        { status: "pending", _id: "6055cb33062eb5153c089122", title: "title1", description: "test description", user: "id", team: "id" },
        { status: "accepted", _id: "6055cb3d062eb5153c089123", title: "title2", description: "test description", user: "id", team: "id" }
    ]
    
    //return index of the element if find else return -1 
    const findIndex = (booking) => bookings.findIndex((b, index) => {
        if (b._id === booking._id) return true
    })
    
    //test 1
    let booking = { status: "pending", _id: "6055cb33062eb5153c089122", title: "title2", description: "test description", user: "id", team: "id" }
    console.log("index >>> ", findIndex(booking))
    //output : 1
    
    //test 2
    booking = { status: "rejected", _id: "6055cb33062eb5153c089198", title: "title3", description: "test description", user: "id", team: "id" }
    console.log("index >>> ", findIndex(booking))
    //output : -1
    
    //test 3
    const id = '6055cb3d062eb5153c089123'
    console.log("index >>> ", findIndex({ _id: id }))
    //output : 2
    

    如果你有一个普通的旧数组,你所能做的就是迭代。数组就是这样,一堆按数组索引排序的对象。今天就来看看这篇文章,对于所有后来者来说,ECMAScript 2015中有一个新的数组方法
    array.prototype.findIndex()
    。公认的答案是很棒的方法。我是ES6语法的粉丝(如果需要对传统浏览器的支持,请使用polyfills)。ES7+ES8将是未来的选择仅供参考,如果您希望能够快速查找,那么您可能不应该使用数组,而应该使用字典(Id、对象)+1,我总是忘记对象上的内置函数。这不会返回索引。这不会回答这个特定问题,但帮了我很多忙!谢谢!这不会返回索引。这个答案很好,因为它实际上通过提供索引来回答这个问题:)@ZeroAbsolute您的应用函数(传递到map)可以返回一个哈希字符串,该字符串应为您的条件给定的每个可能的组合提供唯一的键。例如:
    function hashf(el){return string(el.id)+“”+string(el.name);}
    。这只是一个提示:
    elementPos=array.map(hashf(x)).indexOf(哈希({id:3,name:'Pablo'))
    显然,我提供的散列函数并非对所有情况都有效,因为
    '
    可能会构成您的值的一部分,但这只是一个简单的示例,您可以找出不同的散列方法。如果找不到它,它会返回什么?我假设-1,只是好奇。我将进行实验。@NathanC.Tresch它返回-1,因为这是
    indexOf返回值。大家好,不要使用两个方法
    map,indexOf
    您可以只使用一个名为
    findIndex
    …例如:
    [{id:1},{id:2},{id:3},{id:4}].findIndex(函数(obj){return obj.id==3})或[{id:1},{id:2},{id:3},{id:4}.findIndex==3}
    我相信这是最优雅的解决方案。对于那些担心向后兼容性的人,你可以在上找到
    findIndex
    的polyfill,我在ES6 lint工具中得到一个警告,这里使用的
    obj.id==3
    运算符可能会导致意外的类型转换,因此请改用
    obj.id==3
    运算符,这会导致代表平等
    var items = []
    
    for(var i = 0; i < 1000; i++) {
        items.push({id: i + 1})
    }
    
    var find = 523
    
    var index = -1
    for(var i = 0; i < items.length; i++) {
        if(items[i].id === find) {
            index = i;
            break;
        }
    }
    
    items.findIndex(item => item.id === find)
    
    items.map(item => item.id).indexOf(find);
    
     while(i<myArray.length && myArray[i].data.value!==value){
      i++; 
    }
    // i now hows the index value for the match. 
     console.log("Index ->",i );
    
    //list of bookings
    const bookings = [
        { status: "accepted", _id: "6055cadd062eb5153c089121", title: "This is test title", user: "id", team: "id" },
        { status: "pending", _id: "6055cb33062eb5153c089122", title: "title1", description: "test description", user: "id", team: "id" },
        { status: "accepted", _id: "6055cb3d062eb5153c089123", title: "title2", description: "test description", user: "id", team: "id" }
    ]
    
    //return index of the element if find else return -1 
    const findIndex = (booking) => bookings.findIndex((b, index) => {
        if (b._id === booking._id) return true
    })
    
    //test 1
    let booking = { status: "pending", _id: "6055cb33062eb5153c089122", title: "title2", description: "test description", user: "id", team: "id" }
    console.log("index >>> ", findIndex(booking))
    //output : 1
    
    //test 2
    booking = { status: "rejected", _id: "6055cb33062eb5153c089198", title: "title3", description: "test description", user: "id", team: "id" }
    console.log("index >>> ", findIndex(booking))
    //output : -1
    
    //test 3
    const id = '6055cb3d062eb5153c089123'
    console.log("index >>> ", findIndex({ _id: id }))
    //output : 2