Aller au contenu principal

findLastIndex()

findLastIndex<T>(array, predicate): number

Returns the index of the last element that satisfies the predicate, or -1 if none found.

remarque

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

Array.findLastIndex()


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);