• Register
36,800 points
11 5 4

Let's see today how to check if a value or element exists within a Javascript array . Remember that an array in Javascript is a list of values.

Table of contents:

  • Introduction.
  • Get index of an element within an array.
  • Check if value exists in array.
  • Check if it exists with includes.
  • Conclusion.

Introduction:

Sometimes you need to find the position of a certain element, or maybe just check if it exists within an array, array, vector, or list. In other words, we will see how to check if an element is present . Recently in ES6 a new method was introduced that we will see below.

Get index of an element within an array:

We use indexOf , which I translate as "index of." It is easy, it is a method that has the arrangements and that receives the value to look for. Returns the position of the element, or -1 if it cannot be found. Unlike python, this one does not raise any exceptions.

var agents = ["Will Graham", "Clarice Starling", "Alex Cross"];

var index = agents.indexOf ("Will Graham"); // Find Will Graham Index
// index is 0

var otherIndex = agents.indexOf ("Thomas Pierce"); //Does not exist
// other Index is -1

With this we can obtain the index, which we remember starts counting from 0. That is, the first element has the index 0, the second 1, and so on.

Check if value exists in array:

Previously, only indexOf was used and its result was checked with -1. That is, if the index was -1 then it did not exist. Another method was recently introduced. Let's see both.

Check if it exists with indexOf

Taking the example above, we can see if Thomas Pierce exists like this:

var agents = ["Will Graham", "Clarice Starling", "Alex Cross"];

var index = agents.indexOf ("Thomas Pierce");

if (index! == -1) {
  console.log ("Thomas Pierce is present");
} else {
  console.log ("Not found");
}

We only compare to see if it is -1. In case it is, it is not present within the list.

Check if it exists with includes:

As I said, a more elegant method has been introduced. We can rewrite the above like this:

var agents = ["Will Graham", "Clarice Starling", "Alex Cross"];

if (agents.includes ("Thomas Pierce")) {
  console.log ("Thomas Pierce is present");
} else {
  console.log ("Not found");
}

As the reader can see, the includes method or function returns a Boolean. If it exists, it returns true ; and if not, then it returns false .

Conclusion:

If we need the index, let's use indexOf. If we only want to see if it exists, we use includes. By the way, we did it with strings but it works with numbers anyway. And with other types of data.

36,800 points
11 5 4