In an array of objects, fastest way to find the index of an object whose attributes match a search

In an array of objects, fastest way to find the index of an object whose attributes match a search

I’ve been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:
array[i].id = some number;
array[i].name = some name;

What i want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4.
I suppose I could just do something like :
var indexes = [];
for(i=0; i

for example, returns undefined, as it probably should. Thanks in advance!

Solutions/Answers:

Solution 1:

Maybe you would like to use higher-order functions such as “map”.
Assuming you want search by ‘field’ attribute:

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

Solution 2:

The simplest and easiest way to find element index in array.

ES5 syntax: [{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})

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

Solution 3:

The new Array method .filter() would work well for this:

var filteredArray = array.filter(function (element) { 
    return element.id === 0;
});

jQuery can also do this with .grep()

edit: it is worth mentioning that both of these functions just iterate under the hood, there won’t be a noticeable performance difference between them and rolling your own filter function, but why re-invent the wheel.

Solution 4:

array.forEach(function (elem, i) {  // iterate over all elements of array
    indexes[elem.id] = i;           // take the found id as index for the
});                                 // indexes array and assign i

the result is a look up list for the id. with the given id we get the index of the record.

Related:  JQuery UI min script errors

Solution 5:

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);
    }
}

Solution 6:

Since there’s no answer using regular array find:

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