How to check if a value exists in an array?

The quick and easy way in Javascript!

·

1 min read

How to check if a value exists in an array?

An easy way to check if a value exists in an array, is to use the method indexOf(). The method indexOf() is applied to an array and takes as argument a value and it searches and returns the first index of the position, where the value is in the array. If the value doesn't exists in the array, then the method returns the value -1.
More info here.

So, to solve our problem we can use the indexOf() method in the given array. If the method returns -1, it means that the element doesn't exist in the array, otherwise it exists.

Here is an example code:

let a = ["Dimitrios", "Georgios", "Aleksandros"];

function searchElement(array, element) {
  if (array.indexOf(element) < 0) {
    return false;
  } else {
    return true;
  }
}
console.log(searchElement(a, "Georgios")); // true
console.log(searchElement(a, "Nikolaos")); // false

or in fewer lines:

let a = ["Dimitrios", "Georgios", "Aleksandros"];

const searchElement = (array, element) => array.indexOf(element) < 0 ? false : true

console.log(searchElement(a, "Georgios")); // true
console.log(searchElement(a, "Nikolaos")); // false