I have a JavaScript array of objects like this:
var myArray = [{...}, {...}, {...}];
Each object has unique id
among other pro
You can use .reduce()
, which lets you reduce an Array down to a single value.
var obj_idx = myArray.reduce(function(idx, item, i) {
return item.id === 4 ? i : idx;
}, -1);
The -1
is a default value if no match is found.
If you have multiple uses for this, you may want to make a function factory.
function idxForID(target) {
return function(idx, item, i) {
return item.id === target ? i : idx;
};
}
And then use it like this.
var obj_idx = myArray.reduce(idxForID(4), -1);
If each id is unique, you can do it like this:
o1 = {id:1}
o2 = {id:2}
o3 = {id:3}
o4 = {id:4}
a = [o1,o2,o3,o4]
a.indexOf( a.filter( function(i){return i.id==4} )[0] );
You could also try a recursive function, though @xdazz's looks rather attractive.
var indexOfId = function(arr, id, index) {
if (!index) { index = 0; }
if (arr[index].id == id) {
return index;
}
return ((index += 1) >= arr.length) ? -1 : indexOfId(arr, id, index);
};
var index = myArray.map(function(el) {
return el.id;
}).indexOf(4);
For IE below version 9, map need a patch, or just use a loop.
ES6 Array.findIndex
const myArray = [{id:1}, {id:2}, {id3}];
const foundIndex = myArray.findIndex((el) => (el.id === 3));
Why not simply make a loop ?
function indexOfId(array, id) {
for (var i=0; i<array.length; i++) {
if (array[i].id==id) return i;
}
return -1;
}
The fact that there are many facilities in js (or js libraries) doesn't mean you must not, sometimes, write a loop. That's fast and simple.