gurehbgui
gurehbgui

Reputation: 14674

Check if an element is in an array

I have a JS array of objects like this:

Ident: "2"
Text: "Foo"

Now I want to check if the object with the Ident equal to 2 is in the array. How can I do this? It's not possible with jQuery.inArray because I don't have the whole object, just the Ident.

Upvotes: 1

Views: 163

Answers (3)

serakfalcon
serakfalcon

Reputation: 3531

var found = false;
for (var i =0;i<somearray.length;i++) {
    if (somearray[i].Ident === 2) {
        found = true;
        break;
    }
}

Upvotes: 1

Serg Tomcat
Serg Tomcat

Reputation: 933

As you had mentioned JQuery, you can use "grep" method:

 if (jQuery.grep(arr, function( n ) {
   return ( n.Ident == "2" );
 }).length)
 ...

but it will loop through all elements.

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 237837

You will indeed have to do the loop the long way here:

function findByIdent(array, ident) {
    var i;

    for (i = 0; i < array.length; i++) {
        if (array[i].Ident === ident) {
            return i;
        }
    }

    return -1; // not found
}

If it's any consolation, this used to be the way all is-this-element-in-this-array calls were done!

Note that this presumes that you have an array that looks approximately like this:

[{Ident: "2", Text: "foo"}, {Ident: "3", Text: "bar"}]

Upvotes: 3

Related Questions