How to Check if an Element is Present in an Array in JavaScript?
An array is a data type, which can hold multiple values in a single variable. It is an excellent solution if you have a list of different items and you want to store them. By sorting different elements, it also helps perform searching. Knowing basic array operations is essential to improve your programming skills.
How to Create an Array
An array holds more than one value under a single name. Spaces and line breaks are not important while creating an array. Here is an example of a JavaScript array:
let arr = new Array();
let arr = [];
Very often we need to check whether the element is in an array in JavaScript or not. In this snippet, we are going to learn some methods to do that.
Firstly we’ll have a look at a simple but working solution. We must define statements if element is present in the array, like this:
The array is traversed from index 0 to array.length - 1 index. Notice that we use less than operator (<) instead of not less than equal to (<=). It works in the following way: in the if condition we check the array of the elements and search the array's value, after it we print "element found".
Now we will define for conditions and take a variable for telling if an element found.
If the element found, the flag value will change inside the if condition and that’s how we can check whether it is present or not.
Now let’s consider another method of checking if the element is present in the array or not. It's the includes() method, which is now commonly used.
This method returns true if the array contains the specified element, and false if not, like this:
Let’s see another example:
Example
There exists one more method that can be useful. The indexOf method is used to search the index of an array element. It tells whether the array contains the given element or not. If the given element in JavaScript indexOf method found, it will return the index number of that element. If not, the indexOf returns the -1 value.
Here is how the code looks like:
These two methods have two parameters: element and start. Let’s check them out:
Parameter | Description |
---|---|
element | Required. The element to search for |
start | Optional. Default 0. At which position in the array to start the search |