Error in following code:-
var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOf({id: 'abc'});
What's the syntax for above?
Error in following code:-
var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOf({id: 'abc'});
What's the syntax for above?
You should pass reference to exactly the same object you have defined in the array:
var a = {id: 'abc'},
b = {id: 'xyz'};
var index = [a, b].indexOf(a); // 0
Objects are only equal to each other if they refer to the exact same instance of the object.
You would need to implement your own search feature. For example:
Array.prototype.indexOfObject = function(obj) {
var l = this.length, i, k, ok;
for( i=0; i<l; i++) {
ok = true;
for( k in obj) if( obj.hasOwnProperty(k)) {
if( this[i][k] !== obj[k]) {
ok = false;
break;
}
}
if( ok) return i;
}
return -1; // no match
};
var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOfObject({id: 'abc'}); // 0
Iterate through the array like this:
for(var i = 0, len = x.length; i < len; i++) {
if (x[i].id === 'abc') {
console.log(i);
break;
}
}
Otherwise, you'll have to make sure the pointers are the same for the objects you're trying to look for with indexOf
Let's have some nice code here ;)
Underscore.js provides where
, which is also fairly easy to write in pure JS:
Array.prototype.where = function(props) {
return this.filter(function(e) {
for (var p in props)
if (e[p] !== props[p])
return false;
return true;
});
}
Another (more flexible) function understands either an object or a function as a selector:
Array.prototype.indexBy = function(selector) {
var fn = typeof selector == "function" ? selector :
function(elem) {
return Object.keys(selector).every(function(k) {
return elem[k] === selector[k]
})
}
return this.map(fn).indexOf(true);
}
and then
var x = [{id: 'abc'}, {id: 'xyz'}];
x.indexBy({'id': 'xyz'}) // works
x.indexBy(function(elem) { return elem.id == 'xyz' }) // works too
var o = {}
var x = [o]
console.log(x.indexOf(o))
With x.indexOf({})
you create a new Object the is not present in the array
The following is the most wonderful method:-
var indexId = x.map(function(e) { return e.id; }).indexOf('abc');
as seen in this answer