brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: JavaScript's findLast() searches an array from the end

Javascript
~/tips/tip-javascript-array-findlast

[5, 12, 50, 130, 44].findLast((element) => element > 45);

Finds the last array item that matches a test, without reversing or copying the array.

Need the most recent matching item in a list, like the last error in a log array? The old trick was [...arr].reverse().find(), which copies the whole array first. There is a method for it now.

[5, 12, 50, 130, 44].findLast((element) => element > 45);
// 130

findLast() walks from the end towards the start and returns the first element that passes the test, which is the last one in the array. If nothing matches you get undefined. Its sibling gives you the position:

[5, 12, 50, 130, 44].findLastIndex((element) => element > 45);
// 3

findLastIndex() returns -1 when nothing matches, just like findIndex().

A real example:

const lastError = logEntries.findLast((e) => e.level === "error");

The callback gets the element, its index and the array, same as find().

Caveats. Empty slots in a sparse array are visited as undefined, so a test like (e) => e.level throws on a gap; guard against it if your arrays can have holes. And be careful with a match on a falsy value: findLast() returning 0 or "" is a real result, so check for undefined explicitly. MDN marks both methods widely available since August 2022, so old browsers and old Node versions lack them.

Further reading: MDN: Array.prototype.findLast(), MDN: Array.prototype.findLastIndex()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link