findLast()
findLast<
T>(array,predicate):T|undefined
Iterates over elements from right to left, returning the first element predicate returns truthy for.
This is a polyfill for Array.prototype.findLast (ES2023).
Type Parametersβ
T: Tβ
The type of elements in the array.
Parametersβ
array: readonly T[]β
The array to inspect.
predicate: (value, index, array) => booleanβ
The function invoked per iteration.
Returns: T | undefinedβ
The matched element, or undefined if not found.
Sinceβ
2.0.0
Performanceβ
O(n) time, stops at first match from the end.
Also known asβ
findLast (Lodash, es-toolkit, Remeda, Ramda, Effect) Β· β (Radashi, Modern Dash, Antfu)
Exampleβ
const users = [
{ user: 'barney', active: true },
{ user: 'fred', active: false },
{ user: 'pebbles', active: true }
];
findLast(users, u => u.active);
// => { user: 'pebbles', active: true }
findLast([1, 2, 3, 4, 5], n => n % 2 === 0);
// => 4
How it works?β
Returns the last element that matches the predicate. Iterates from right to left.
Use Casesβ
Find the last matching element πβ
Locate the last element that satisfies a condition. Perfect for finding the most recent match 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 lastLogin = findLast(activities, (a) => a.type === "login");
// => { type: "login", time: "12:00" }
Find the last valid entry before errorsβ
Identify 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 lastSuccess = findLast(operations, (op) => op.status === "success");
// => { id: 2, status: "success" }
Locate the last element meeting a thresholdβ
Find 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 lastHotDay = findLast(temperatures, (temp) => temp >= 25);
// => 28
Find the last visible element in a scroll containerβ
Locate the last item currently visible in a scrollable container. Essential for scroll-to-bottom detection and "jump to latest" features.
const messages = [
{ id: 1, text: "Hello", offsetTop: 0 },
{ id: 2, text: "How are you?", offsetTop: 60 },
{ id: 3, text: "Fine thanks", offsetTop: 120 },
{ id: 4, text: "See you later", offsetTop: 180 },
];
const scrollBottom = container.scrollTop + container.clientHeight;
const lastVisible = findLast(messages, (msg) => msg.offsetTop < scrollBottom);
// => { id: 3, text: "Fine thanks" } if scrollBottom is 150
// Show "new messages" indicator if last visible != last message
if (lastVisible?.id !== messages[messages.length - 1].id) {
showNewMessagesBadge();
}