findLast And findLastIndex Search From The End
Reach the most recent matching record with findLast and findLastIndex, which scan the array from the tail and return undefined or -1 when nothing matches.
Code
// findLast / findLastIndex (ES2023): 从末尾向前扫描,不用先 reverse
const deploys = [
{ env: 'staging', ok: true, at: '10:02' },
{ env: 'prod', ok: false, at: '10:05' },
{ env: 'prod', ok: true, at: '10:12' },
{ env: 'prod', ok: false, at: '10:20' },
];
// 最近一次失败的生产部署:findLast 从尾部开始找
const lastFailed = deploys.findLast((d) => d.env === 'prod' && !d.ok);
console.log('last failed:', `${lastFailed.env}@${lastFailed.at}`);
// findLastIndex:无匹配时返回 -1
const okIndex = deploys.findLastIndex((d) => d.env === 'prod' && d.ok);
console.log('last ok prod index:', okIndex, deploys[okIndex].at);
// 对照 find:从前往后,拿到的是第一条而不是最近一条
console.log('first prod:', deploys.find((d) => d.env === 'prod').at);
console.log('missing:', deploys.findLast((d) => d.env === 'canary') ?? 'none');Output
Captured from a sandboxed run of this snippet in the build pipeline.
last failed: prod@10:20
last ok prod index: 2 10:12
first prod: 10:05
missing: noneHow it works
Module-level bindings hold the data — deploys, lastFailed, okIndex — with no function scope in between.
Using it
Running the file prints labeled results such as last failed:, last ok prod index:, first prod: — each operation’s effect is visible in the output.
Key statements
const okIndex = deploys.findLastIndex((d) => d.env === 'prod' && d.ok);
const lastFailed = deploys.findLast((d) => d.env === 'prod' && !d.ok);
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `deploys`, `lastFailed`, `okIndex`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.