
In the next tutorial, we will discuss Array some() method with the help of examples. Hope that you will have understood how to find the index of the first matching element in an array based on specific test condition using findIndex() method. In this tutorial, you have learned array findIndex() method in JavaScript with the help of example programs. The general syntax of the findIndex() method in JavaScript is: // Arrow functionĪrr.findIndex((element) => ) => name = 'Belly') Let index = numbers.findIndex(isGreater) Ĭonsole.log("Index of first greater number than 2: " +index) To find index of a given element in array in JavaScript, call indexOf() method on this array and pass the element to find as argument to this indexOf(). Find the index of first greater number than 2. Callback function to check greater number than 2.

index is the index of the current element being processed. The testFn takes three arguments: element is the current element in the array. Otherwise, it returns -1 if no matching is found.įor example, the following snippet code returns the index of the first number that’s greater than 2. The findIndex () takes two arguments: 1) testFn The testFn is a function to execute on each element in the array until the function returns true, indicating that the element has been found. Syntax: array.find (function (currentValue, index, arr),thisValue) Example 1: This example uses the find () method to search the element. It finds the element in the DOM tree by traversing through the root to the leaf. If the item is a primitive value, like a string or number, you can use the indexOf method of an array: const letters = const index = letters.In other words, find() method of array returns the index of first array element that satisfies provided testing function (i.e. JavaScript find () method: The find () method is used to find all the descendant elements of the selected element. Suppose you have the value of an item which is contained in an array, and you want to get its index. Here is how to retrieve the index of an item in a JS array based on its value
