nbar
nbar

Reputation: 6158

jQuery.inArray(), how to use it right?

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.

Upvotes: 424

Views: 812824

Answers (20)

Alladin Khan
Alladin Khan

Reputation: 1

var college_year = [2021,2022,2023, 2024];
var arraylen = college_year.length;
// Use an array to store the dynamic arrays
var year_arrays = [];

for (var i = 0; i < arraylen; i++) {
  if (jQuery.inArray(college_year[i], year_arrays) === -1) {
    year_arrays.push(college_year[i]);
  }
}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Upvotes: 0

Sahi Repswal
Sahi Repswal

Reputation: 340

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

Upvotes: 13

M Amir Shahzad
M Amir Shahzad

Reputation: 318

the shortest and simplest way is.

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

if(arrayHere[any key want to search])   
   console.log("yes found in array");

Upvotes: -5

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

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>

Upvotes: 3

Joeneter10
Joeneter10

Reputation: 11

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

Upvotes: 1

MistyDawn
MistyDawn

Reputation: 903

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

Upvotes: 3

Saurabh Solanki
Saurabh Solanki

Reputation: 2204

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

Upvotes: 22

Alberto Cerqueira
Alberto Cerqueira

Reputation: 1409

Man, check the doc.

for example:

var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);

Upvotes: 1

/^(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.

Upvotes: 2

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

Upvotes: 3

DDan
DDan

Reputation: 8276

I usually use

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

or

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

Upvotes: 9

6502
6502

Reputation: 114461

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

Upvotes: 29

William Hu
William Hu

Reputation: 16141

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

Upvotes: 1

Patsy Issa
Patsy Issa

Reputation: 11293

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.

Upvotes: 28

Dennis
Dennis

Reputation: 14455

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)

Upvotes: 883

Jason Watmore
Jason Watmore

Reputation: 4701

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

Upvotes: 14

Johan
Johan

Reputation: 35194

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

Upvotes: 4

Darvex
Darvex

Reputation: 3644

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

Upvotes: 4

Jon
Jon

Reputation: 437336

$.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");
} 

Upvotes: 70

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

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.

Upvotes: 14

Related Questions