Skip to content

Instantly share code, notes, and snippets.

@ironstrider
Last active March 5, 2022 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ironstrider/b8ef0eaa73857861af47dc4817998b0b to your computer and use it in GitHub Desktop.
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
// 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