lastIndexOf()
lastIndexOf<
T>(array,value,fromIndex?):number
Gets the index at which the last occurrence of value is found in array.
DEPRECATED
Use array.lastIndexOf(value) directly instead.
Reason:
Native equivalent method now available
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
array: T[]โ
The array to search.
value: Tโ
The value to search for.
fromIndex?: numberโ
The index to search from.
Returns: numberโ
The index of the matched value, or -1 if not found.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
findLastIndex (Effect) ยท lastIndexOf (Lodash, es-toolkit, Ramda) ยท โ (Remeda, Radashi, Modern Dash, Antfu)
Exampleโ
const numbers = [1, 2, 3, 2, 4];
// โ Deprecated approach
const index = lastIndexOf(numbers, 2);
console.log(index); // 3
// โ
Recommended approach
const indexNative = numbers.lastIndexOf(2);
console.log(indexNative); // 3
How it works?โ
Returns the index of the last occurrence of a value.
Deprecated: Use array.lastIndexOf() directly.
Native Equivalentโ
// โ lastIndexOf(arr, value)
// โ
arr.lastIndexOf(value)
Use Casesโ
Find last occurrence ๐โ
Get the index of the last matching element.
const items = ["a", "b", "a", "c", "a"];
items.lastIndexOf("a");
// => 4
Find last match before positionโ
Search backwards from a specific index.
const chars = ["a", "b", "a", "c", "a"];
chars.lastIndexOf("a", 3);
// => 2
Check duplicate positionโ
Find if element appears multiple times.
const values = [1, 2, 3, 2, 4];
values.indexOf(2) !== values.lastIndexOf(2);
// => true (duplicates exist)