Table of Contents
Syntax and explanationThe findIndex() method returns the index of the first element in array that satisfies the given testing function. If no element of the array satisfies the testing condition, it returns -1.
The syntax of the findIndex() method is as follows
The above findIndex() method takes two arguments:
A. testFuncThe testFunc() is a function that is used to execute a condition on each element of the array until the function returns true, indicating that the element satisfying the condition was found.
The testFn() takes three arguments:
currentValue: This indicates the current element in the array being processed.
index: Indicates the index of the current element being processed.
arr: This is the array that the findIndex() was called upon.
The findIndex() executes testFunc() for every element of the array and if true is returned by the testFunc(), findIndex() returns the index of that element and does not check for the rest of the array elements
Example CodeThe following example uses findIndex() method to find the first occurrence of a prime number in a given array.
- Google Chrome 45.0 and above
- Mozilla Firefox 25.0 and above
- Microsoft Edge 12.0 and above
- Internet Explorer does not Support findIndex() method
- Safari 7.1 and above
- Opera 32 and above