Alex
Alex

Reputation: 68406

jQuery $.inArray() returns 0

if you have a array like ('a', 'b') and check $.inArray('a', thearray); you get the index, which is 0, and could be false. So you need to check the result further and it's annoying...

Is there a quick method trough which I can get only true/false, and not the indexes?

basically I have a string in a html5 data attribute: data-options="a,b,c" and 3 a, b, c variables in javascript that must take true/false values based on what's inside data-options...

Upvotes: 3

Views: 6977

Answers (3)

jAndy
jAndy

Reputation: 235962

You can achieve that by invoking the binary NOT operator.

if( ~$.inArray('a', thearray) ) {
}

Explained in detail here: typeofnan.blogspot.com/2011/04/did-you-know-episode-ii.html

Upvotes: 7

nickf
nickf

Reputation: 545995

Yep, compare to -1.

if ($.inArray('a', thearray) === -1) {
    // not found
}

You could wrap that into another function if it really bugs you:

function myInArray(needle, haystack) {
    return $.inArray(needle, haystack) !== -1;
}

Upvotes: 4

Šime Vidas
Šime Vidas

Reputation: 185883

Test against -1:

$.inArray('a', arr) !== -1

The above expression will return true/false.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

Source: http://api.jquery.com/jQuery.inArray/

Upvotes: 6

Related Questions