2

Error in following code:-

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

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

What's the syntax for above?

Sangram Singh
  • 7,161
  • 15
  • 50
  • 79
  • 1
    That's not a syntax problem. [Two objects with different references in memory are different in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators). – Denys Séguret Nov 14 '13 at 14:16

6 Answers6

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
VisioN
  • 143,310
  • 32
  • 282
  • 281
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
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
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

Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
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
georg
  • 211,518
  • 52
  • 313
  • 390
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

philipp
  • 15,947
  • 15
  • 61
  • 106
0

The following is the most wonderful method:-

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

as seen in this answer

Community
  • 1
  • 1
Sangram Singh
  • 7,161
  • 15
  • 50
  • 79