Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created November 29, 2023 21:17
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 skarllot/f2b399fa9e5fec18e6666ba61b5f01c0 to your computer and use it in GitHub Desktop.
Save skarllot/f2b399fa9e5fec18e6666ba61b5f01c0 to your computer and use it in GitHub Desktop.
Find last index of an array (mirror of ES2015 findIndex function)
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param array The source array to search in
* @param predicate find calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
*/
export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number {
let l = array.length;
while (l--) {
if (predicate(array[l], l, array))
return l;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment