Menu Close

How to check if value exists in array or not using jquery

jquery check if value exists in array

In the below example, we learn about how to check if a value exists in an array or not using jQuey.InArray() method. So, if we have a value and need to check whether the value exists in an associative array or not. We can easily verify if the value exists in an array of objects using jQuey.InArray() method instead of using a for loop.

Here, the array of variable contains values as colors. The blue color contains an array of variable arrColors. So if it exists in this variable, it will display the associative message of that variable. Follow the below example to check this out.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to check if value exists in array or not using jquery</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> 
</head>
<body>
</body>
    <script>
        $(document).ready(function(){
            var arrColors = ['green', 'blue', 'orange', 'yellow', 'white', 'red'];
            if ($.inArray('blue', arrColors) >= 0) {
                console.log('Value exists in array variable');
            } else {
                console.log('Value not exists');
            }
        });  
    </script>
</html> 

Output:

jquery check if value exists in array
Posted in HTML, jQuery, Web Technologies

You can also read...