In this article, We will see the different ways to find if a value exists in an array.
With the help of the above function, we can easily find out the position of the specified value in the array. It mainly returns the position of the value in array, if the value does not exist then -1 is returned.
Example:
const fruits = ['Mango','Apple','Banana','Orange','Grapes'];
// Find in Array
console.log(fruits.indexOf('Banana')); // Result: 2
// when value in not in array
console.log(fruits.indexOf('abcd')); // Result: -1
The includes() method determines whether an array contains a specified element. This method returns true if the array contains the element, and false if not.
Example:
const fruits1 = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits1.includes("Mango")); // Result: true
console.log(fruits1.includes("Pears")); // Result: false
We can also find the value in the array without any javascript function.
const fruits = ['Mango','Apple','Banana','Orange','Grapes'];
function findValueInArray(value,arr){
let result = "Doesn't exist";
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
result = 'Exist';
break;
}
}
return result;
}
console.log(findValueInArray('Banana', fruits)); // Result : Exist
console.log(findValueInArray('abc', fruits)); // Result : Doesn't exist