How to Check If Value Exists in a Javascript Array
In this example, we will show you how to check if the value exists in a javascript array. there are three types of checks if a value exists in a javascript array. so let’s go see three types.
You can use indexOf() function for check the value exists in an array or no. it is function returns the true and false value. see below example of indexOf().
1 2 3 4 5 6 7 8 | <script> var myArray = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; if(myArray.indexOf("Mango") !== -1){ alert("Value exists!"); } else{ alert("Value does not exists!"); } </script> |
You can use includes() function for check the value exists in an array or no. it is function returns the true and false value. see below example of includes().
1 2 3 4 | <script> var myArray = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; alert(myArray.includes("Banana")); // Outputs: true </script> |
Finally, You can use the inArray() function for check the value exists in an array or no. it is function returns the true and false value. see below example of inArray().
1 2 3 4 5 6 7 8 | <script type="text/javascript"> var myArray = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; if ($.inArray('Banana', myArray) >= 0) { alert("Value exists!"); }else { alert("Value does not exists!"); } </script> |
Please follow and like us: