416

First time I work with jQuery.inArray() and it acts kinda strange.

If the object is in the array, it will return 0, but 0 is false in Javascript. So the following will output: "is NOT in array"

var myarray = [];
myarray.push("test");

if(jQuery.inArray("test", myarray)) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}

I will have to change the if statement to:

if(jQuery.inArray("test", myarray)==0)

But this makes the code unreadable. Especially for someone who doesn't know this function. They will expect that jQuery.inArray("test", myarray) gives true when "test" is in the array.

So my question is, why is it done this way? I realy dislike this. But there must be a good reason to do it like that.

Ed DeGagne
  • 3,250
  • 1
  • 30
  • 46
nbar
  • 6,028
  • 2
  • 24
  • 65

20 Answers20

870

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.

So, to check if an item is in the array, use:

if(jQuery.inArray("test", myarray) !== -1)
Dennis
  • 14,210
  • 2
  • 34
  • 54
  • 17
    CoffeeScript: `if jQuery.inArray('test', myarray) isn't -1` – Joshua Pinter Oct 27 '14 at 15:20
  • 11
    Of course, you could always define your own, more intuitive, function like `$.isInArray = function(test,array) { return $.inArray(test, array) !== -1; };` – Wesley Smith Nov 10 '15 at 06:46
  • 1
    Or shorter: `$.isInArray = function(item, array) { return !!~$.inArray(item, array); };` (I would keep cryptic code like that in a well named function to keep the intention clear though :) ) – Dennis Nov 10 '15 at 06:53
  • 2
    Thanks @Chips_100 for showing us visual learners how to do it right, it'd be nice if jQuery could update to include that in their own example. – asherrard Dec 01 '15 at 15:21
  • 1
    @notblakeshelton You're absolutely correct. I think autocorrect snuck that apostrophe in there. – Joshua Pinter Jul 30 '16 at 05:33
  • What is the need of type checking for result. no need of `!==`, only `!=` is sufficient, isn't it? – Diablo Sep 15 '16 at 16:16
  • 4
    you can also use `if( $.inArray(test, array) > -1) { // do stuff }` – MistyDawn Jul 06 '18 at 20:38
  • Here `if(jQuery.inArray("test", myarray) != -1)` any **- ( negative )** number shall be placed right ! __Why everyone using -1__ ?. as @MistyDawn stated it!! – Deepa MG Oct 30 '19 at 08:42
68

$.inArray returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
} 
Jon
  • 428,835
  • 81
  • 738
  • 806
29

The right way of using inArray(x, arr) is not using it at all, and using instead arr.indexOf(x).

The official standard name is also more clear on the fact that the returned value is an index thus if the element passed is the first one you will get back a 0 (that is falsy in Javascript).

(Note that arr.indexOf(x) is not supported in Internet Explorer until IE9, so if you need to support IE8 and earlier, this will not work, and the jQuery function is a better alternative.)

6502
  • 112,025
  • 15
  • 165
  • 265
  • 2
    I have to agree. The name of inArray is confusing. It seems it should return a boolean, but it does exactly the same as indexOf – Enrique Moreno Tent Apr 05 '16 at 09:21
  • 1
    Everytime I `$.inArray` used at the beginning of some code I have to go fix a bug in, I groan. Anyway, this should be the accepted answer. – Aluan Haddad Jul 19 '17 at 15:57
  • This should be the accepted answer. Why would you want to take your pen, drain the blue ink and fill it with red ink when you can use a red marker from the beginning – David Fariña Mar 09 '23 at 15:23
27

The answer comes from the first paragraph of the documentation check if the results is greater than -1, not if it's true or false.

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

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.

Community
  • 1
  • 1
Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
20

instead of using jQuery.inArray() you can also use includes method for int array :

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

check official post here

Saurabh Solanki
  • 2,146
  • 18
  • 31
14

jQuery inArray() method is use to search a value in an array and return its index not a Boolean value. And if the value was not found it’ll return -1.

So, to check if a value is present in an array, follow the below practice:

myArray = new Array("php", "tutor");
if( $.inArray("php", myArray) !== -1 ) {

    alert("found");
}

Reference

Hassan Amir Khan
  • 645
  • 8
  • 13
13

The inArray function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.

When inArray returns 0 it is indicating that the first argument was found at the first position of the supplied array.

To use inArray within an if statement use:

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}

inArray returns -1 when the first argument passed to the function is not found in the array passed as the second argument.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
13

Or if you want to get a bit fancy you can use the bitwise not (~) and logical not(!) operators to convert the result of the inArray function to a boolean value.

if(!!~jQuery.inArray("test", myarray)) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}
Jason Watmore
  • 4,521
  • 2
  • 32
  • 36
  • 4
    The use of bitwise operators is generally forbidden/frowned upon in the common JavaScript coding standards. So if you're using a linter (jshint, eslint etc.) chances are you won't get this through code review. Solution works though. – jhrr Feb 24 '16 at 14:00
12

inArray returns the index of the element in the array. If the element was not found, -1 will be returned else index of element.

if(jQuery.inArray("element", myarray) === -1) {
    console.log("Not exists in array");
} else {
    console.log("Exists in array");
}
Sahi Repswal
  • 190
  • 3
  • 12
9

I usually use

if(!(jQuery.inArray("test", myarray) < 0))

or

if(jQuery.inArray("test", myarray) >= 0)
DDan
  • 8,068
  • 5
  • 33
  • 52
3

jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()

Darvex
  • 3,624
  • 2
  • 23
  • 39
3

It will return the index of the item in the array. If it's not found you will get -1

Johan
  • 35,120
  • 54
  • 178
  • 293
3

If we want to check an element is inside a set of elements we can do for example:

var checkboxes_checked = $('input[type="checkbox"]:checked');

// Whenever a checkbox or input text is changed
$('input[type="checkbox"], input[type="text"]').change(function() {
    // Checking if the element was an already checked checkbox
    if($.inArray( $(this)[0], checkboxes_checked) !== -1) {
        alert('this checkbox was already checked');
    }
}
3

var abc = {
      "partner": {
        "name": "North East & Cumbria (EDT)",
        "number": "01915008717",
        "areas": {
        "authority": ["Allerdale", "Barrow-in-Furness", "Carlisle"]
        }
      }
    };
    
    
    $.each(abc.partner.areas, function(key, val){
     console.log(val);
      if(jQuery.inArray("Carlisle", val)) {
        console.log(abc.partner.number);
    }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
abhinavsinghvirsen
  • 1,853
  • 16
  • 25
2
/^(one|two|tree)$/i.test(field) // field = Two; // true
/^(one|two|tree)$/i.test(field) // field = six; // false
/^(раз|два|три)$/ui.test(field) // field = Три; // true

This is useful for checking dynamic variables. This method is easy to read.

2

$.inArray() does the EXACT SAME THING as myarray.indexOf() and returns the index of the item you are checking the array for the existence of. It's just compatible with earlier versions of IE before IE9. The best choice is probably to use myarray.includes() which returns a boolean true/false value. See snippet below for output examples of all 3 methods.

// Declare the array and define it's values
var myarray = ['Cat', 'Dog', 'Fish'];

// Display the return value of each jQuery function 
// when a radio button is selected
$('input:radio').change( function() {

  // Get the value of the selected radio
  var selectedItem = $('input:radio[name=arrayItems]:checked').val();
  $('.item').text( selectedItem );
  
  // Calculate and display the index of the selected item
  $('#indexVal').text( myarray.indexOf(selectedItem) );
  
  // Calculate and display the $.inArray() value for the selected item
  $('#inArrVal').text( $.inArray(selectedItem, myarray) );
  
  // Calculate and display the .includes value for the selected item
  $('#includeVal').text( myarray.includes(selectedItem) );
});
#results { line-height: 1.8em; }
#resultLabels { width: 14em; display: inline-block; margin-left: 10px; float: left; }
label { margin-right: 1.5em; }
.space { margin-right: 1.5em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Click a radio button to display the output of
&nbsp;<code>$.inArray()</code>
&nbsp;vs. <code>myArray.indexOf()</code>
&nbsp;vs. <code>myarray.includes()</code>
&nbsp;when tested against
&nbsp;<code>myarray = ['Cat', 'Dog', 'Fish'];</code><br><br>

<label><input type="radio" name="arrayItems" value="Cat"> Cat</label>
<label><input type="radio" name="arrayItems" value="Dog"> Dog</label>
<label><input type="radio" name="arrayItems" value="Fish"> Fish</label>  
<label><input type="radio" name="arrayItems" value="N/A"> ← Not in Array</label>
<br><br>

<div id="results">
  <strong>Results:</strong><br>
  <div id="resultLabels">
    myarray.indexOf( "<span class="item">item</span>" )<br>
    $.inArray( "<span class="item">item</span>", myarray )<br>
    myarray.includes( "<span class="item">item</span>" )
  </div>
  <div id="resultOutputs">
    <span class="space">=</span><span id="indexVal"></span><br>
    <span class="space">=</span><span id="inArrVal"></span><br>
    <span class="space">=</span><span id="includeVal"></span>
  </div>
 </div>
MistyDawn
  • 856
  • 8
  • 9
  • It should be noted that `$.inArray` should be the golden standard if you have access to the jQuery library. Otherwise, JavaScript `.indexOf` with a polyfill for IE8 should be used instead. Stay away from that modern stuff like `.includes()`. – Alexander Dixon Dec 04 '18 at 14:18
1

Man, check the doc.

for example:

var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
Alberto Cerqueira
  • 1,339
  • 14
  • 18
1

For some reason when you try to check for a jquery DOM element it won't work properly. So rewriting the function would do the trick:

function isObjectInArray(array,obj){
    for(var i = 0; i < array.length; i++) {
        if($(obj).is(array[i])) {
            return i;
        }
    }
    return -1;
}
Joeneter10
  • 11
  • 1
0

Just no one use $ instead of jQuery:

if ($.inArray(nearest.node.name, array)>=0){
   console.log("is in array");
}else{
   console.log("is not in array");
}
William Hu
  • 15,423
  • 11
  • 100
  • 121
  • I'm just curious why? Is there some uncommon compatibility issue this causes? I've never had any kind of issue using the `$` instead of `jQuery`. – MistyDawn Jul 06 '18 at 22:38
-6

the shortest and simplest way is.

arrayHere = ['cat1', 'dog2', 'bat3']; 

if(arrayHere[any key want to search])   
   console.log("yes found in array");
M Amir Shahzad
  • 190
  • 2
  • 16
  • can you please share some code, i will check and let you know about it. it should work. i am already doing it – M Amir Shahzad Jul 30 '20 at 19:56
  • @RyanArief can you please share some code , I will let you know why its not working. – M Amir Shahzad Aug 27 '20 at 15:29
  • var arrayHere = ['cat1', 'dog2', 'bat3']; if(arrayHere[0]) alert("yes found in array"); if(arrayHere[3]) alert("yes found second in array"); – M Amir Shahzad Aug 27 '20 at 15:32
  • on the line "if(arrayHere[any key want to search])", you should add some "/' or js would see it as variable.we never know programmer level who search this topic so pls specify more detail on your code. – Ryan Arief Aug 30 '20 at 10:53