findLast Scans Readonly Arrays From The End
findLast and findLastIndex search backwards through readonly arrays and return undefined or -1 when nothing matches, typed as T | undefined at the call site.
Code
const events: ReadonlyArray<{ kind: string; at: number }> = [
{ kind: 'push', at: 10 },
{ kind: 'pr', at: 20 },
{ kind: 'push', at: 30 },
];
// 从尾部向前扫描:返回最后一个匹配项或 undefined
const lastPush = events.findLast((e) => e.kind === 'push');
console.log(lastPush?.at, '| kind:', lastPush?.kind);
// findLastIndex 给出最后一个匹配的下标,无匹配返回 -1
const lastPrIndex = events.findLastIndex((e) => e.kind === 'pr');
console.log('last pr index:', lastPrIndex);
// 无匹配时的兜底:?? 后备值让 undefined 变成显式结果
console.log(events.findLast((e) => e.kind === 'tag') ?? 'none');Output
Captured from a sandboxed run of this snippet in the build pipeline.
30 | kind: push
last pr index: 1
noneThe behavior line by line
Demo state sits in top-level bindings: lastPush, lastPrIndex.
What to watch for
- Free of dependencies in its very construction — no registry hit, no lockfile line.
Using it
Output lines are prefixed (last pr index:), so each output line keeps its step visibly attached.
Key statements
const lastPrIndex = events.findLastIndex((e) => e.kind === 'pr');
const lastPush = events.findLast((e) => e.kind === 'push');
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `lastPush`, `lastPrIndex`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.