In this article, we will see how to check element or value is in an array or not. In short, if we have a value and want to check whether the value exists in an associative array or not using multiple methods
While manipulating an array checking element exists in an array or not and finding the element’s index is very common. We can also check it manually by running the loop. But jQuery provides jQuery.inArray() method to check element exists in an array or not.
The $.inArray() or jQuery.inArray() function is an in-built method. It takes one parameter as input and searches it into an array. If an element is found in an array then it will return its index otherwise it will return -1.
Check Element Exists Using jQuery.inArray() Method
Here, we will use the inArray() method to find elements that exist in jQuery. In this example, we will define an array of students and then check particular student exists in an array or not. Let’s take an example for it:
var students = ['Alex', 'John', 'Raj', 'Tony', 'Mary'];
if ($.inArray('John', students) === -1) {
console.log('Student not found in array');
} else {
console.log('Student found in array');
}
The above example will check given student is in an array or not and based on the result we will just print the message.
Output :
Student found in array
Check Element Exists Using Array.indexOf() Method
The indexOf() method helps us to find out an index of elements in an array. The indexOf() method takes one parameter which is value and finds out an index of that value. If a value is not found in an array then it will return -1.
Let’s take an example to check element exists or not in an array using the indexOf() method:
$(document).ready(function(){
var students = ['Alex', 'John', 'Raj', 'Tony', 'Mary'];
if (students.indexOf('John') === -1) {
console.log('Student not found in array');
} else {
console.log('Student found in array');
}
});
It will print output as previously but this time using indexOf() method.
Conclusion
In this article, we have demonstrated whether to check value exists in an array or not using multiple methods like inArray() and indexOf() in jQuery.