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.

Answers:

Answer

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

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

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.

Answer

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

Answer

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

I usually use

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

or

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

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

Answer

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.

Answer

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

Answer

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

Answer

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

Answer

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');
    }
}
Answer
/^(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.

Answer

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

Answer

Man, check the doc.

for example:

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

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

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

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>

Answer

the shortest and simplest way is.

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.