findindex method in javascript
The
findIndex() method in JavaScript is an Array method that returns the index of the first element in an array that satisfies a provided testing function. If no element in the array satisfies the condition, it returns -1.
Syntax:
arr.findIndex(callback(element, index, array), thisArg)
Parameters:
callback: A function that is executed for each element in the array. It takes up to three arguments:element: The current element being processed in the array.index(optional): The index of the current element being processed.
array(optional): The arrayfindIndex()was called upon.
thisArg (optional): A value to be used as this when executing the callback function.Return Value:
The index of the first element in the array that satisfies the provided test function.
-1 if no element satisfies the condition.
Example:
const numbers = [2, 8, 1, 3, 4];
// Find the index of the first odd number
const firstOddIndex = numbers.findIndex(function(element) {
return element % 2 !== 0;
});
console.log(firstOddIndex); // Output: 2 (because 1 is at index 2)
// Find the index of a number greater than 5
const greaterThanFiveIndex = numbers.findIndex(element => element > 5);
console.log(greaterThanFiveIndex); // Output: 1 (because 8 is at index 1)
// Find the index of an element that doesn't exist
const nonExistentIndex = numbers.findIndex(element => element === 10);
console.log(nonExistentIndex); // Output: -1