This post will discuss how to find the index of the first occurrence of a given value in an array in JavaScript.

1. Using Array.prototype.indexOf() function

The indexOf() method returns the index of the first occurrence of the given element in an array and returns -1 when it doesn’t find a match. It uses a strict equality Algorithm (=== operator) to compare elements.

Download  Run Code

2. Using Array.prototype.findIndex() function

The findIndex() method returns the index of the first occurrence of an element in the array that satisfies the given predicate. It returns -1 when no element is matched. Here’s what the code would look like:

Download  Run Code

3. Using Underscore/Lodash Library

The Underscore and Lodash library offer the _.indexOf method, similar to JavaScript’s native .indexOf() method. The following code example demonstrates the usage of the _.indexOf method.

Download Code

4. Using jQuery

Alternatively, with jQuery, you can use the $.inArray method, which works similarly to JavaScript’s native indexOf() method. The $.inArray() method is a misnomer as it doesn’t return a boolean value but returns the first index of the array element. Its usage is demonstrated below:

Download Code

That’s all about finding the index of an element in an array in JavaScript.