Implement a function findLastIndex(array, predicate, [fromIndex=array.length-1]) that takes an array of values, a function predicate, and an optional fromIndex number argument. findLastIndex iterates over elements of the array from right to left.
The function returns the index of the first element that satisfies the predicate when iterating backwards from fromIndex.
array (Array): The array to inspect.predicate (Function): The function invoked per iteration.[fromIndex=array.length-1] (number): The index to start searching from (towards the left).Predicate signature: The predicate function is invoked with three arguments: (value, index, array).
value: The current element being iterated.index: The index of the current element.array: The original input array.(number): Returns the index of the found element, else -1.
const arr = [5, 4, 3, 2, 1]; // Indices: 0, 1, 2, 3, 4
// Search for the element > 3, starting from the end (index 4).
findLastIndex(arr, (num) => num > 3); // => 1
// Start searching backwards from index 3.
// Check index 3: 2 > 1 is true. Stop.
findLastIndex(arr, (num) => num > 1, 3); // => 3
// Start searching backwards from index 3.
// Check index 3: 2 < 1 is false.
// Check index 2: 3 < 1 is false.
// Check index 1: 4 < 1 is false.
// Check index 0: 5 < 1 is false. Reached start and no element found.
findLastIndex(arr, (num) => num < 1, 3); // => -1
Your function should handle negative and out-of-bound fromIndex values.
fromIndex: negative integers count back from the last item in the array. -1 means the last element in the array, -2 means the second last element, and so on.fromIndex is less than 0 (e.g., fromIndex is -10 for an array of length 5), the search starts from index 0.fromIndex >= array.length, the search starts from the last index (array.length - 1).