findLastIndex()
findLastIndex<
T>(array,predicate):number
Returns the index of the last element that satisfies the predicate, or -1 if none found.
Prefer this over native Array.findLastIndex() for ES2020 compatibility.
Type Parametersβ
T: Tβ
The type of elements in the array.
Parametersβ
array: readonly T[]β
The source array to inspect.
predicate: (value, index, array) => booleanβ
The function invoked per iteration.
Returns: numberβ
The index of the found element, else -1.
See Alsoβ
Sinceβ
2.0.0
Performanceβ
O(n) time, O(1) space, reverse iteration with early return on match.
Also known asβ
findLastIndex (Lodash, es-toolkit, Remeda, Ramda, Effect) Β· β (Radashi, Modern Dash, Antfu)
Exampleβ
findLastIndex([1, 2, 3, 4, 3, 2, 1], (v) => v > 2);
// => 4
findLastIndex(
[{ name: 'Bob', age: 30 }, { name: 'Alice', age: 30 }],
(u) => u.age === 30
);
// => 1
How it works?β
Returns the index of the last element that matches the predicate. Iterates from right to left.
Use Casesβ
Find the last occurrence index of a matching element πβ
Locate the index of the last element that satisfies a condition. Perfect for finding the most recent match position in logs, history, or ordered data.
const activities = [
{ type: "login", time: "08:00" },
{ type: "purchase", time: "09:30" },
{ type: "login", time: "12:00" },
{ type: "logout", time: "18:00" },
];
const lastLoginIndex = findLastIndex(activities, (a) => a.type === "login");
// => 2
Find the last valid entry index before errorsβ
Identify the position of the last successful or valid record in a sequence. Perfect for error recovery, checkpointing, or rollback scenarios.
const operations = [
{ id: 1, status: "success" },
{ id: 2, status: "success" },
{ id: 3, status: "failed" },
{ id: 4, status: "failed" },
];
const lastSuccessIndex = findLastIndex(
operations,
(op) => op.status === "success"
);
// => 1
Locate the last element index meeting a numeric thresholdβ
Find the index of the last value that passes a numeric condition. Perfect for analyzing trends, finding peaks, or locating threshold crossings.
const temperatures = [18, 22, 25, 30, 28, 24, 19, 17];
const lastHotDayIndex = findLastIndex(temperatures, (temp) => temp >= 25);
// => 4 (value: 28)
Find the last visible item index for scroll anchoringβ
Locate the index of the last item visible in the viewport for scroll restoration. Essential for virtual scroll implementations and scroll position preservation.
const items = [
{ id: 1, top: 0 },
{ id: 2, top: 80 },
{ id: 3, top: 160 },
{ id: 4, top: 240 },
{ id: 5, top: 320 },
];
const viewportBottom = container.scrollTop + container.clientHeight;
const lastVisibleIndex = findLastIndex(items, (item) => item.top < viewportBottom);
// => 3 (item at top: 240 is last visible)
// Use for scroll restoration after data refresh
scrollToIndex(lastVisibleIndex);