Skip to main content

findLast()

findLast<T>(array, predicate): T | undefined

Iterates over elements from right to left, returning the first element predicate returns truthy for.

note

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