3

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...

2

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

What you lose in speed you more than make up for in sheer, unadulterated manliness.
to uglify + clearify this, you could also use !!~$.inArray('a', thearray)
@Alex: !! forces the result to be a boolean value. So -4 or 11 for instance would get turned into true, whereas 0 for instance gets turned into false. Anyway, I don't recommend it here, since it looks pretty alien :-)
nah, I'm using it like a = !!~$.inArray('a', thearray); :D thanks!
6

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/

Comments

4

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;
}

1 Comment

I like wrapping logic in a reusable component. Kudos @nickf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.