Skip to main content

How to determine whether a value exists in an array in javascript

how-to-determine-whether-value-exists-in-an-array-in-javascript


Question: How to determine whether an array contains a value

Answer:

More than one method to solve this problem. let's see one by one.

First: using while loop

Array.prototype.contains = function(value) { var i = this.length; while (i--) { if (this[i] == value) { return true; } } return false; } myArray = ["Red","Green", "Black", "Orange", "Yellow"] console.log(myArray.contains("Black")); console.log(myArray.contains("Blue")); 

Output:

true false 


Second: Another way to check, whether the value exists in the array or not. If value exits, it will return 'true' otherwise false.

myArray = ["Red","Green", "Black", "Orange", "Yellow"] myArray.includes("Green"); 

Output:

true 


Third: This is the easiest way to find the value that exists in the array. We are using 'for loop'. If value exits, it will return 'true' otherwise false.

myArray = ["Red","Green", "Black", "Orange", "Yellow"]; function isValueExists(array, value){ for(var i=0; i< array.length;i++){ if(array[i]==value){ return true; } } return false; } console.log(isValueExists(myArray, 'Black')); console.log(isValueExists(myArray, 'blue')); 

Output:

true false 


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments