This post will discuss how to check whether an array contains a certain value in JavaScript.

1. Using Array.includes() function

In modern browsers, you can use the Array.includes() method to check the presence of an element in an array, returning true or false as appropriate. It uses the sameValueZero algorithm to determine whether the given element is found.

Download  Run Code

2. Using Array.indexOf() function

The indexOf() method returns the specified element index in the array and returns -1 when it doesn’t find a match. It uses a strict equality Algorithm (=== operator) to compare elements. This is demonstrated below:

Download  Run Code

3. Using jQuery

With jQuery, you can use the $.inArray method, which works in a similar manner as the JavaScript’s native indexOf() method. The following example demonstrates.

Download Code

4. Using Underscore Library

Alternatively, the Underscore library offers the _.contains method that returns true if the given value is found in the array and false otherwise. It has two alias – _.include and _.includes.

Download Code

5. Using Lodash Library

Lodash Library also offers a similar method called the _.includes method to determine whether a value is present in an array. It uses SameValueZero for equality comparisons.

Download Code

6. Using Array.some() function

The Array.some() method returns true if at least one element passes the provided predicate and returns false otherwise. To check for an element’s existence in an array with the some() method, the predicate should make a strict comparison of each element against the specified value. Here’s what the code would look like:

Download  Run Code

7. Using Array.find() function

Like the Array.some() method, the Array.find() method takes a callback function, but instead of returning a boolean value, it returns the value of the first matching element and undefined when no matching element is found.

Download  Run Code

8. Using Array.findIndex() function

Like the Array.find() method, the Array.findIndex() method takes a callback function, but instead of returning the matched value, it returns its index.

Download  Run Code

9. Using Array.filter() function

The Array.filter() method takes a callback function and returns an array of matching elements. If no elements were matches, an empty array is returned. The idea is to check for the length property of the returned array to decide if the specified value is found in the array or not. This is demonstrated below:

Download  Run Code

10. Extending Array prototype

Finally, you can write our own custom routine for old browsers that don’t support JavaScript native indexOf() and includes() method. You can easily do this by extending the Array prototype:

Download  Run Code

That’s all about determining whether an array contains a certain value in JavaScript.