Use indexOf()
You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];var a = "Mango";checkArray(a, fruits);function checkArray(a, fruits) { // Check if a value exists in the fruits array if (fruits.indexOf(a) !== -1) { return document.write("true"); } else { return document.write("false"); }}
Use include() Method
ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number:
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];alert(fruits.includes("Banana")); // Outputs: truealert(fruits.includes("Coconut")); // Outputs: falsealert(fruits.includes("Orange")); // Outputs: truealert(fruits.includes("Cherry")); // Outputs: false
For further reference checkout here