The Wayback Machine - http://web.archive.org/web/20210910224630/https://www.geeksforgeeks.org/javascript-array-findindex-method/amp/

JavaScript Array findIndex() Method

Below is the example of the Array findIndex() method to find the index of positive number from an array.

The arr.findIndex() method used to return the index of the first element in a given array that satisfies the provided testing function. Otherwise, -1 is returned.

Syntax:

array.findIndex(function(currentValue, index, arr), thisValue)

Parameters: This method accepts five parameters as mentioned above and described below:

Return value:It returns the array element index if any of the elements in the array pass the test, otherwise it returns -1.



Below examples illustrate the Array findIndex() function in JavaScript:

Codes for the above function are defined as follows:

Program 1:




<script>
    // Input array contain elements
    var array = [10, 20, 30, 110, 60];
  
    // Testing method (element > 25).
    function finding_index(element) {
        return element > 25;
    }
  
    // Printing the index of element which is satisfies
    document.write(array.findIndex(finding_index));
</script>

Output:

2

Program 2:




<script>
    // Number is prime or not prime.
    function isPrime(n) {
        if (n === 1) {
            return false;
        } else if (n === 2) {
            return true;
        } else {
            for (var x = 2; x < n; x++) {
                if (n % x === 0) {
                    return false;
                }
            }
            return true;
        }
    }
  
    // Printing -1 because prime number is not found.
    document.write([4, 6, 8, 12].findIndex(isPrime));
    document.write("<br />")
    // Printing 2 the index of prime number (7) found.
    document.write([4, 6, 7, 12].findIndex(isPrime));
</script>

Output:

-1
2

Supported Browsers: The browsers supported by JavaScript Array findIndex() method are listed below:




Article Tags :