Why jQuery.inArray does not work with an array of objects

I have an array of objects

var arr = [
        {"id" : "1", "description" : "one"},
        {"id" : "2", "description" : "two"},
        {"id" : "3", "description" : "three"}]

I need to get an index, for example, for an object with id = "2". I do

var index = jQuery.inArray( {"id" : "2", "description" : "two"}, arr )

In the index, I get -1.

Jsfiddle

+4
source share
3 answers

Because it inArrayuses ===elements to compare, and different objects are never to ===each other. (They are also not to ==each other.)

eg:.

var a = {"foo": "bar"};
var b = {"foo": "bar"};
console.log(a === b); // "false"

You will need to create a method to compare them for equivalence, and then do the search yourself.

+8
source

You can use a function that performs a callback:

function arrayFind(arr, fn) {
    for( var i = 0, len = arr.length; i < len; ++i ) {
        if( fn(arr[i]) ) {
            return i;
        }
    }
    return -1;
}

var arr = [
        {"id" : "1", "description" : "one"},
        {"id" : "2", "description" : "two"},
        {"id" : "3", "description" : "three"}
];

var result = arrayFind(arr, function(v){
    return v.id === "2" && v.description === "two";
});
console.log(result) //1
+5
source

As TJ said, it inArrayuses ===( indexOfactually, but it's the same thing), so even the same literals are compared not equal. Here is a workaround:

var index = jQuery.inArray( 
    JSON.stringify({"id" : "2", "description" : "two"}), 
    $.map(arr, JSON.stringify) )

http://jsfiddle.net/7kg9P/1/

+1
source

All Articles