Open In App

Difference Between indexOf and findIndex function of array

The task is to differentiate between the indexOf() and findIndex() methods of JavaScript. we’re going to discuss both approaches.

JavaScript indexOf() Method: This method is used to find the index of the first occurrence of the elements provided for search as the argument to the function. 



Syntax: 

arr.indexOf(element[, index])

Parameters: 



Return value: This method returns the index of the string (0-based) where the search value is found for the first time. If the search value cannot be found in the string then the function returns -1.

JavaScript findIndex() Method: This method returns the index of the first element of the given array which satisfies the testing function. 

Syntax: 

array.findIndex(fun(curValue, index, arr), thisValue)

Parameters: 

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

Example 1: In this example, indexOf() method is used. 




let array = ["Geeks", "GFG", "geeks", "Geeks"];
 
console.log("Array: [" + array + "]");
 
console.log("First index of 'Geeks' is "
    + array.indexOf('Geeks'));

Output
Array: [Geeks,GFG,geeks,Geeks]
First index of 'Geeks' is 0

Example 2: In this example, findIndex() function is used. 




let array = [1, 3, 4, 5, 6, 7, 8, 9];
 
console.log("Array: [" + array + "]");
 
function getEven(n) {
    if (n % 2 == 0) {
        return 1;
    }
    return 0;
}
 
console.log("First even number in array is at index "
        + array.findIndex(getEven));

Output
Array: [1,3,4,5,6,7,8,9]
First even number in array is at index 2

Conclusion:


Article Tags :