Last active
March 5, 2022 22:28
-
-
Save ironstrider/b8ef0eaa73857861af47dc4817998b0b to your computer and use it in GitHub Desktop.
Search javascript array from the *right* to find the (index of the) *last* element satisfying a condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns the index of the last array element that satisfies a condition function. Otherwise, returns -1 | |
// Similar to Array.prototype.findIndex, but finds the *last* element by searching from the right | |
// Parameters are exactly the same as findIndex: | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | |
function findLastIndex(array, callbackFn, thisArg) { | |
for (let i = array.length - 1; i >= 0; i--) { | |
if(callbackFn.call(thisArg, array[i], i, array)) { | |
return i | |
} | |
} | |
return -1 | |
} | |
nums = [3,1,4,1,5] | |
console.log(findLastIndex(nums, e => e === 4)) | |
console.log(findLastIndex(nums, e => e === 1)) | |
console.log(findLastIndex(nums, e => e === 7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment