How in jQuery Check if Value Exists In Array or Not ?

/ / 0 Comments

Check if value exists in array jQuery: Here in this article will see how in jQuery check if array contains a value or not. In short, if we have a value and want to check whether the value exists in an associative array or not.

Without making a Forloop, just by using jQuery.inArray() method we can easily verify if values are available in an array of objects.

The jQuery.InArray() is a built-in jquery method, used to find a given value within an array. If the value is available it returns its index, and if value not exists then it returns -1.

Usage of jQuery.inArray() method

Here we have an array variable that contains values as fruit names. Now we want to check if the fruit mango value is contained in our array variable (arrFruits), and display the respective console message. 

Our final jQuery code look like as written below:

var arrFruits = ['apple', 'mango', 'orange', 'grapes', 'banana'];

if ($.inArray('mango', arrFruits) >= 0) {
    console.log('Value exists in Array variable');
} else {
    console.log('Value Not exists');
}

View Demo


Output:



Conclusion:
Here we use $.InArray method to check if the value already exists in an array variable without making any ForLoop.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments