Open In App

JavaScript Array findIndex() Method

JavaScript Array findIndex() method iterates over array elements, returning the index of the first element passing a test. If no match, returns -1. Doesn’t execute for empty elements, preserving the original array.

Array findIndex() Syntax

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

Array findIndex() Parameters

Return value

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



Array findIndex() Examples

Example 1: Finding Indices that contain odd numbers

Here, the method findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1.




function isOdd(element, index, array) {
    return (element % 2 == 1);
}
 
console.log(([4, 6, 8, 12].findIndex(isOdd)));

Output

-1




Explanation:

Example 2: Finding Indices that contain positive numbers

Here, the method findIndex() finds all the indices that contain positive numbers. Since 0.30 is a positive number therefore it returns its index.




// input array contain some elements.
let array = [-10, -0.20, 0.30, -40, -50];
 
// function (return element > 0).
let found = array.findIndex(function (element) {
    return element > 0;
});
 
// Printing desired values.
console.log(found);

Output
2




Explanation

Example 3: Finding Indices that contain numbers greater than 25

Here, the method findIndex() finds all the indices that contain numbers greater than 25. Since 30 is greater than 25 therefore it returns its index.




// Input array contain elements
let 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
console.log(array.findIndex(finding_index));

Output
2




Explanation

Example 4: Finding Indices that contain prime numbers.

Here, the method findIndex() finds all the indices that contain prime numbers.




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

Output
-1
2




Explanation:

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:


Article Tags :