How to check value exists in array or not in jQuery

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 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 is exist in 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 element is found in 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 element 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 array or not and based on result we will just print message.

Output :

Student found in array

Check Element Exists Using Array.indexOf() Method

The indexOf() method helps us to find out index of element in array. The indexOf() method takes one parameter which is value and finds out an index of that value. If value is not found in array then it will return -1.

Let's take example for check element exists or not in an array using 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 array or not using multiple methods like inArray() and indexOf() in jQuery.