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.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// 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: none

How 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

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`.