Loading article...
The findIndex() method returns the index of the first element that satisfies the provided testing function, or -1 if none is found.
-1: If no element matches the condition, return -1.Array.prototype.customFindIndex = function(callbackFn, thisArg) { // Iterate over the array using a for loop for (let i = 0; i < this.length; i++) { // Call the callback function with the current element, index, and array // .call() is used to bind the this value inside the callback function if (callbackFn.call(thisArg, this[i], i, this)) { return i; // Return the index of the first matching element } } return -1; // Return -1 if no element matches the condition }; // Example usage: const array = [5, 12, 8, 130, 44]; // Find the index of the first element greater than 10 const foundIndex = array.customFindIndex(element => element > 10); console.log(foundIndex); // Output: 1 (because 12 is the first element greater than 10)
Iteration over the array:
for loop. The loop will go from index 0 to this.length - 1.Executing the callback function:
callbackFn is executed with three arguments: this[i] (the current element), i (the index of the element), and this (the array itself).i.Return -1 if no match is found:
-1.element => element > 10: The callback function checks if an element is greater than 10.[5, 12, 8, 130, 44], it will return the index 1, because 12 is the first element greater than 10.200 in the same array), the method will return -1.console.log(array.customFindIndex(element => element > 200)); // Output: -1
findIndex method.for loop to iterate over the array and callbackFn.call() to ensure the correct context for the this inside the callback function.-1 if no element satisfies the condition.Test your understanding with 3 quick questions