C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Array findIndex() methodThe JavaScript array findIndex() method returns the index of first element of the given array that satisfies the provided function condition. It returns -1, if no element satisfies the condition. SyntaxThe findIndex() method is represented by the following syntax: array.findIndex(callback(value,index,arr),thisArg) Parametercallback - It represents the function that executes each element. value - The current element of an array. index - It is optional. The index of current element. arr - It is optional. The array on which findIndex() method operated. thisArg - It is optional. The value to use as this while executing callback. ReturnThe index of first element of the array that satisfies the function condition. JavaScript Array findIndex() method exampleLet's see some examples of findIndex() method. Example 1Let's see a simple example of findIndex() method. <script> var arr=[5,22,19,25,34]; var result=arr.findIndex(x=>x>20); document.writeln(result) </script> Output: 1 Example 2In this example, we will find the index of prime number using findIndex() method. <script> function isPrime(value, index, arr) { var start = 2; while (start <= Math.sqrt(value)) { if (value % start++ < 1) { return false; } } return value > 1; } document.writeln([8, 4, 7, 22].findIndex(isPrime)); </script> Output: 2
Next TopicJavaScript Array
|