How to Check Value Exist in Array using Javascript/Jquery

How to check if value exist in array using Javascript and Jquery . Javascript and Jquery provides in-built function indexOf() and $.inArray(). In this tutorial, i’ll explain how to use these functions and how we can create our own custom method as well.

Javascript Array and it’s Method.

Difference Between Undefined and Null value in Javascript.

Javascript Custom Method to check Value Exist in Array

To check whether the value exist in array, first method comes in our mind is to use loop and check each value. If we find the match then value exist in array otherwise value does not exist in an array.

In algorithm terms it’s a Linear Search. The time complexity of this method is O(n).

If you don’t know how to create an array in Javascript then check my previous tutorial on Array in Javascript .

How to Reverse String in Javascript.

Let’s create a function which return index of an element if it is found in array otherwise -1.

Javascript indexOf() method to Check Value Exist in Array

Javascript indexOf() function searches an element in an array. If value exist then it returns the position of an element. Otherwise return -1 if the value is not found.

 

PHP code to check if value exists in Array.

Jquery inArray() method to Check Value Exist in an Array

$.inArray() work similar to indexOf() method. It searches the element in an array, if it’s found then it return it’s index. Return -1 if it’s not found.

Top websites to Learn Coding Online .

Conclusion

I tried my best to explain the usage of inArray and indexOf method. If you want to add something please let’s us know through your comment so that every reader take the advantage.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.