jQuery.inArray(), how to use it right?
JavascriptJqueryJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
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)
Solution 2 - Javascript
$.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");
}
Solution 3 - Javascript
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.
Solution 4 - Javascript
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.)
Solution 5 - Javascript
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
Solution 6 - Javascript
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");
}
Solution 7 - Javascript
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");
}
Solution 8 - Javascript
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.
Solution 9 - Javascript
I usually use
if(!(jQuery.inArray("test", myarray) < 0))
or
if(jQuery.inArray("test", myarray) >= 0)
Solution 10 - Javascript
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");
}
Solution 11 - Javascript
jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()
Solution 12 - Javascript
It will return the index of the item in the array. If it's not found you will get -1
Solution 13 - Javascript
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');
}
}
Solution 14 - Javascript
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>
Solution 15 - Javascript
/^(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.
Solution 16 - Javascript
$.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
<code>$.inArray()</code>
vs. <code>myArray.indexOf()</code>
vs. <code>myarray.includes()</code>
when tested against
<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>
Solution 17 - Javascript
Man, check the doc.
for example:
var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
Solution 18 - Javascript
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;
}
Solution 19 - Javascript
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");
}
Solution 20 - Javascript
the shortest and simplest way is.
arrayHere = ['cat1', 'dog2', 'bat3'];
if(arrayHere[any key want to search])
console.log("yes found in array");