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.
This question is related to
javascript
jquery
the shortest and simplest way is.
arrayHere = ['cat1', 'dog2', 'bat3'];
if(arrayHere[any key want to search])
console.log("yes found in array");
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");
}
$.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_x000D_
var myarray = ['Cat', 'Dog', 'Fish'];_x000D_
_x000D_
// Display the return value of each jQuery function _x000D_
// when a radio button is selected_x000D_
$('input:radio').change( function() {_x000D_
_x000D_
// Get the value of the selected radio_x000D_
var selectedItem = $('input:radio[name=arrayItems]:checked').val();_x000D_
$('.item').text( selectedItem );_x000D_
_x000D_
// Calculate and display the index of the selected item_x000D_
$('#indexVal').text( myarray.indexOf(selectedItem) );_x000D_
_x000D_
// Calculate and display the $.inArray() value for the selected item_x000D_
$('#inArrVal').text( $.inArray(selectedItem, myarray) );_x000D_
_x000D_
// Calculate and display the .includes value for the selected item_x000D_
$('#includeVal').text( myarray.includes(selectedItem) );_x000D_
});
_x000D_
#results { line-height: 1.8em; }_x000D_
#resultLabels { width: 14em; display: inline-block; margin-left: 10px; float: left; }_x000D_
label { margin-right: 1.5em; }_x000D_
.space { margin-right: 1.5em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Click a radio button to display the output of_x000D_
<code>$.inArray()</code>_x000D_
vs. <code>myArray.indexOf()</code>_x000D_
vs. <code>myarray.includes()</code>_x000D_
when tested against_x000D_
<code>myarray = ['Cat', 'Dog', 'Fish'];</code><br><br>_x000D_
_x000D_
<label><input type="radio" name="arrayItems" value="Cat"> Cat</label>_x000D_
<label><input type="radio" name="arrayItems" value="Dog"> Dog</label>_x000D_
<label><input type="radio" name="arrayItems" value="Fish"> Fish</label> _x000D_
<label><input type="radio" name="arrayItems" value="N/A"> ? Not in Array</label>_x000D_
<br><br>_x000D_
_x000D_
<div id="results">_x000D_
<strong>Results:</strong><br>_x000D_
<div id="resultLabels">_x000D_
myarray.indexOf( "<span class="item">item</span>" )<br>_x000D_
$.inArray( "<span class="item">item</span>", myarray )<br>_x000D_
myarray.includes( "<span class="item">item</span>" )_x000D_
</div>_x000D_
<div id="resultOutputs">_x000D_
<span class="space">=</span><span id="indexVal"></span><br>_x000D_
<span class="space">=</span><span id="inArrVal"></span><br>_x000D_
<span class="space">=</span><span id="includeVal"></span>_x000D_
</div>_x000D_
</div>
_x000D_
jQuery.inArray() returns index of the item in the array, or -1 if item was not found. Read more here: jQuery.inArray()
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.
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");
}
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.
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;
}
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
Man, check the doc.
for example:
var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
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.)
var abc = {_x000D_
"partner": {_x000D_
"name": "North East & Cumbria (EDT)",_x000D_
"number": "01915008717",_x000D_
"areas": {_x000D_
"authority": ["Allerdale", "Barrow-in-Furness", "Carlisle"]_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
$.each(abc.partner.areas, function(key, val){_x000D_
console.log(val);_x000D_
if(jQuery.inArray("Carlisle", val)) {_x000D_
console.log(abc.partner.number);_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
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");
}
I usually use
if(!(jQuery.inArray("test", myarray) < 0))
or
if(jQuery.inArray("test", myarray) >= 0)
It will return the index of the item in the array. If it's not found you will get -1
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");
}
$.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");
}
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');
}
}
/^(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.
Source: Stackoverflow.com