JavaScript arr.findIndex() function is used to find the index of the first element that satisfies the condition checked by the argument function from the given array. Suppose you want to find the index of the first element of the array that is even.
Syntax:
array.findIndex(function(element, index, arr), thisValue)
Parameters: The argument to this function is another function that defines the condition to be checked for each element of the array. This function itself takes three arguments:
- array: This is the array of the current element.
- index: This is the index of the current element
- element: This is the current value of the element
Another argument thisvalue is used to tell the function to use this value when executing the argument function.
Return value This function returns the index value of the first element that satisfies the given condition. If no element satisfies the condition then it returns -1
Below examples will illustrate the JavaScript Array findIndex() Function:
Example 1: In this example, we will see the use of the arr.findIndex() method. This method returns -1 if an element is not found in the array.
JavaScript
<script> // JavaScript to illustrate findIndex() function function isOdd(element, index, array) { return (element % 2 == 1); } function func() { var array = [4, 6, 8, 12]; console.log(array.findIndex(isOdd)); } func(); </script> |
Output: In this example, the function findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1.
-1
Then the function as an argument to findIndex() checks for even numbers for all the elements of the array. The first element that this function returns as even, its index will be returned by the findIndex() function as the answer.
Output: In this example, the function findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1.
-1
Example 2: In this example, the Javascript findIndex() function returns the index of the first odd number that is present in the array.
JavaScript
<script> // JavaScript to illustrate findIndex() function function isOdd(element, index, array){ return (element % 2 == 1); } function func() { var array = [4, 6, 7, 12]; console.log(array.findIndex(isOdd)); } func(); </script> |
Output:
2
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.