How to check value exists in array or not in jQuery

How to Check Value Exists in Array or not using jQuery? This is a common task in web development when working with arrays. If you have a value and need to confirm whether it exists in an array, you can do it in different ways using jQuery or plain JavaScript.

While manipulating arrays, checking if a value exists and finding its index are frequent operations. You could write a manual loop, but jQuery makes it easier with the jQuery.inArray() method, which quickly checks for a value inside an array.

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.