How to Check If a Value Exists in an Array in JavaScript
source link: https://www.laravelcode.com/post/how-to-check-if-a-value-exists-in-an-array-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Check If a Value Exists in an Array in JavaScript
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:
<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:
<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>
Author : Harsukh Makwana
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK