Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery.inArray doesn't work on array of objects

I have array of objects

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

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

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

In index I get -1.

JsFiddle

like image 710
vborutenko Avatar asked Oct 01 '13 08:10

vborutenko


People also ask

How to check value in array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

What is jQuery object?

A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties: length. context. selector.


3 Answers

Because inArray uses === to compare elements, and different objects are never === to one another. (They're also not == to one another.)

E.g.:

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

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

like image 164
T.J. Crowder Avatar answered Oct 05 '22 01:10

T.J. Crowder


You can use a function that takes 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
like image 21
Esailija Avatar answered Oct 05 '22 03:10

Esailija


As TJ said, inArray uses === (indexOf actually, but that's the same thing), therefore even identical literals are compared non equal. Here's a workaround:

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

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

like image 39
georg Avatar answered Oct 05 '22 02:10

georg