Check Element is in array or not in jquery

In this article, we will see how to check element or value is in 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 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 in-built method. It's takes one parameter as input and search it into array. If element found in array then it will return it's index otherwise it will returns -1.

Check Element Exists Using jQuery.inArray() Method

Here, we will use the inArray() method to find element is exists in jQuery. In this example, we will define an array of students and then check particular student is exists in array or not. Let's take 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');
}

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 find out index of that value. If value not found in array then it will return -1.

Let's take same example for check element exist or not in 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 same output as previous but this time using indexOf method.

Conclusion

In this article, we have demonstrated to check value exists in array or not using multiple methods like inArray() and indexOf() in jQuery.


Share your thoughts

Ask anything about this examples