DEV Community

Zaid Rehman
Zaid Rehman

Posted on • Edited on

Stage 3: Array find from last

Proposal for the .findLast() and .findLastIndex() methods on array and typed array.

Motivation
Finding an element in an array is a very common programming pattern.
It can improve performance by avoiding obvious overhead and improve the constant factors in the time complexity. It can be useful in some performance-sensitive scenarios. eg: React render function.

Core Feature
Adds Array.prototype.findLast and Array.prototype.findLastIndex.

This would behave the same as Array.prototype.find and Array.prototype.findIndex but would iterate from the last to the first.

Code examples

const array = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }];

array.find(n => n.value % 2 === 1); // { value: 1 }
array.findIndex(n => n.value % 2 === 1); // 0

// ======== Before the proposal =========== 

// find
[...array].reverse().find(n => n.value % 2 === 1); // { value: 3 }

// findIndex
array.length - 1 - [...array].reverse().findIndex(n => n.value % 2 === 1); // 2
array.length - 1 - [...array].reverse().findIndex(n => n.value === 42); // should be -1, but 4

// ======== In the proposal =========== 

// find
array.findLast(n => n.value % 2 === 1); // { value: 3 }

// findIndex
array.findLastIndex(n => n.value % 2 === 1); // 2
array.findLastIndex(n => n.value === 42); // -1
Enter fullscreen mode Exit fullscreen mode

Polyfills
https://github.com/zloirock/core-js#array-find-from-last

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️