Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery inArray doesn't work when the first element matches

I'm trying to check an array that I create as to whether or not a value is in the array (anywhere) at all or not. If the value is anywhere in the array it needs to do one thing, else another.

var Arr = [false, false, false, false, false];
// It works with the following:
// Arr = [true, false, false, false, false]

if(!$.inArray(false, Arr))
{
        //False is not in the array at all - so continue with code  
}
else
{
       //False was found in the array
}

So this above code is working as if the if statement is true, however it clearly isn't.

If I change the array to: true, false, false, false, false the if statement is then false though, as it should be.

Basically what I need this code to do is to only be true if every value in the array is true.

like image 336
Dylan Cross Avatar asked Nov 30 '22 22:11

Dylan Cross


2 Answers

$.inArray returns the index of the item or -1 if no items were found:

if ($.inArray(false, Arr) > -1) {
  // found
} else {
  // not found
}

Always useful to check the docs first: http://api.jquery.com/jQuery.inArray/

like image 81
elclanrs Avatar answered Mar 06 '23 17:03

elclanrs


jQuery.inArray( value, array [, fromIndex ] ) Returns: Number

Description: Search for a specified value within an array and return its index (or -1 if not found).

inArray returns an integer!

So when it is at index at 0 it would be a falsely value!

You need to check > -1

like image 22
epascarello Avatar answered Mar 06 '23 17:03

epascarello