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)