How To Check If A Value Exists In An Array In JavaScript
Maybe your like
Topic: JavaScript / jQueryPrev|Next
Answer: Use the indexOf() Method
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:
Example
Try this code » <script> var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; // Check if a value exists in the fruits array if(fruits.indexOf("Mango") !== -1){ alert("Value exists!") } else{ alert("Value does not exists!") } </script>ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number, as you can see here:
Example
Try this code » <script> var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; alert(fruits.includes("Banana")); // Outputs: true alert(fruits.includes("Coconut")); // Outputs: false alert(fruits.includes("Orange")); // Outputs: true alert(fruits.includes("Cherry")); // Outputs: false </script>All modern browsers supports the includes() method and it is preferred for modern applications.
Please check out the tutorial on JavaScript Arrays to learn more about the arrays.
Related FAQ
Here are some more FAQ related to this topic:
- How to remove duplicate values from a JavaScript array
- How to remove a specific item from an array in JavaScript
- How to loop through an array in JavaScript
Tag » Add Element If Not In Array Javascript
-
Array.push() If Does Not Exist? - Stack Overflow
-
Array.push() Element If Does Not Exist Using JavaScript | Bobbyhadz
-
Js Add To Array If Not Exists Code Example
-
Push To Array If Not Exist Javascript Code Example - Code Grepper
-
5 Way To Append Item To Array In JavaScript
-
How To Check If Array Includes A Value In JavaScript? - Samantha Ming
-
totype.push() - JavaScript - MDN Web Docs
-
Array - JavaScript - MDN Web Docs
-
Check If An Item Is In An Array In JavaScript - FreeCodeCamp
-
JavaScript Array Includes() Method - W3Schools
-
Array Methods - The Modern JavaScript Tutorial
-
Add An Item To The Beginning Of An Array In JavaScript Or Node.js
-
Check If The Value Exists In Array In Javascript - Javatpoint
-
Javascript Array Push: How To Add Element In Array - AppDividend
-
How To Check If Key Exists In JavaScript Object/Array - Stack Abuse
-
How To Add Elements Into An Array In JavaScript - Linux Hint
-
How To Check If Value Exists In An Array Using Javascript? - Flexiple
-
JavaScript Arrays - Tips, Tricks And Examples - CodinGame