2

Error in following code:-

var x = [{id: 'abc'}, {id: 'xyz'}];

var index = x.indexOf({id: 'abc'});

What's the syntax for above?

1

6 Answers 6

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

It didn't work when i tried it though.
This is working for me..!!
3

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

3 Comments

this[i].k --> this[i][k].
@VisioN You saw nothing! :p
@Kolink Yeah, yeah, yeah... ;)
1

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

Comments

1

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

Comments

0
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

Comments

0

The following is the most wonderful method:-

var indexId = x.map(function(e) { return e.id; }).indexOf('abc');

as seen in this answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.