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:
- element: This parameter specifies the element to be searched.
- index: This parameter specifies from which index search to start.
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:
- fun: This parameter specifies a function to be run for every element of the array.
- curValue: This parameter specifies the value of the current element.
- index: This parameter specifies the array index of the current element.
- arr: This parameter specifies the array object with the current element belongs.
- thisValue: This parameter specifies a value to be passed to the function to be used as its “this” value. If this is empty, the value “undefined” will be used.
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.
Javascript
let array = [ "Geeks" , "GFG" , "neveropen" , "Geeks" ]; console.log( "Array: [" + array + "]" ); console.log( "First index of 'Geeks' is " + array.indexOf( 'Geeks' )); |
Array: [Geeks,GFG,neveropen,Geeks] First index of 'Geeks' is 0
Example 2: In this example, findIndex() function is used.
Javascript
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)); |
Array: [1,3,4,5,6,7,8,9] First even number in array is at index 2
Conclusion:
- The indexOf() method is used when we want to find the first occurrence of a specified element and the element is known.
- The findIndex() method is used when we want to specify a particular condition to that element.
- JavaScript indexOf() method takes direct element is specified so it is useful when we are working with array of objects.
- JavaScript findIndex() method takes a callback function which returns the value of the element whose index is to be found.