findLast and findLastIndex in JavaScript
Intermediate · 3 min read
Sometimes the item you want is the last one that matches, not the first. The latest error in a log, the most recent payment over a limit, the last time a sensor read above 5. Searching from the start would find the oldest match and also waste time reading the whole list. JavaScript has two methods that search backwards: findLast and findLastIndex.
In this tutorial you will use both, compare them with find, and look at the older workaround of reversing a copy, which finds the right item but reports the wrong index. You should know find, findIndex and arrow functions. If those are new, the previous exercise on find and filter covers them.
A quick reminder: predicates
A predicate is a function that takes one item and returns true or false. find(pred) returns the first item for which pred is true. findIndex(pred) returns its index, or -1.
const readings = [3, 8, 2, 9, 4];
console.log(readings.find((n) => n > 5)); // 8
console.log(readings.findIndex((n) => n > 5)); // 1
Two readings are above 5: the 8 at index 1 and the 9 at index 3. find stops at the first.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
11 Search from the other end
fairFind the last element matching a predicate, and its index. Then check what happens if you reach for a reversed copy instead.
Stuck? Three hints, smallest first
- 1.
findLastandfindLastIndexwalk from the end towards the start. - 2.
lastIndexOftakes a value;findLastIndextakes a predicate. - 3. Reversing a copy finds the right element but the wrong index: you would have to convert it back with
length - 1 - i.
Step 1: findLast
findLast works like find, but it starts at the last item and walks towards the first.
const readings = [3, 8, 2, 9, 4];
console.log(readings.findLast((n) => n > 5)); // 9
Step 2: findLastIndex
findLastIndex gives the index of that last match. The index is still counted from the start of the array, as usual.
const readings = [3, 8, 2, 9, 4];
console.log(readings.findLastIndex((n) => n > 5)); // 3
lastIndexOf sounds similar, but it looks for an exact value, like lastIndexOf(9). findLastIndex takes a predicate, so it can answer questions like "greater than 5".
Step 3: when nothing matches
const readings = [3, 8, 2, 9, 4];
console.log(readings.findLast((n) => n > 99)); // undefined
console.log(readings.findLastIndex((n) => n > 99)); // -1
The same "not found" values as find and findIndex.
Step 4: the old workaround, and its bug
Before these methods existed, people reversed a copy and searched that. [...readings] makes the copy, so the original isn't flipped.
const readings = [3, 8, 2, 9, 4];
const reversed = [...readings].reverse();
console.log(reversed); // [ 4, 9, 2, 8, 3 ]
console.log(reversed.find((n) => n > 5)); // 9: the right value
const reversedIndex = reversed.findIndex((n) => n > 5);
console.log(reversedIndex); // 1: the wrong index
The value is right. The index is not: 1 is the 9's position in the reversed copy. In the original, the 9 is at index 3. Using 1 on the original would point at the 8.
Step 5: converting the index back
To turn a position in the reversed copy into a position in the original, subtract it from the last index, length - 1.
const readings = [3, 8, 2, 9, 4];
const reversedIndex = [...readings].reverse().findIndex((n) => n > 5);
console.log(readings.length - 1 - reversedIndex); // 3
5 - 1 - 1 is 3, which is correct. It works, but it is an easy line to forget, and forgetting it gives an off-by-something bug that only shows up when the match isn't in the middle. findLastIndex gives 3 directly.
Step 6: count the work
Add a counter to see how many items each search looks at, this time searching for the 4 at the end.
const readings = [3, 8, 2, 9, 4];
let lastCalls = 0;
readings.findLast((n) => { lastCalls++; return n === 4; });
let firstCalls = 0;
readings.find((n) => { firstCalls++; return n === 4; });
console.log(lastCalls); // 1
console.log(firstCalls); // 5
Both found the same 4. findLast needed one look, find needed five. On a long log where the item you want is recent, searching from the right end saves real work.
The full solution
The panel searches the readings from both ends, shows the reversed-copy workaround with its index converted back, and prints the call counts. Press Run to see the output.
const readings = [3, 8, 2, 9, 4];
let lastCalls = 0;
const lastFour = readings.findLast((n) => { lastCalls++; return n === 4; });
let firstCalls = 0;
const firstFour = readings.find((n) => { firstCalls++; return n === 4; });
// The pre-findLast idiom, and the index bug that comes with it.
const reversed = [...readings].reverse();
const reversedIndex = reversed.findIndex((n) => n > 5);
console.log('findLast(n > 5) :', readings.findLast((n) => n > 5));
console.log('findLastIndex(n > 5) :', readings.findLastIndex((n) => n > 5));
console.log('find(n > 5) :', readings.find((n) => n > 5), '<- the first one instead');
console.log('--- the reversed-copy workaround ---');
console.log('index in the reversed copy:', reversedIndex);
console.log('converted back :', readings.length - 1 - reversedIndex);
console.log('predicate calls: findLast', lastCalls, ' find', firstCalls);
console.log('both found the same value:', lastFour === firstFour);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('findLast returns the last match', readings.findLast((n) => n > 5), 9);
test('findLastIndex returns its position', readings.findLastIndex((n) => n > 5), 3);
test('find returns the first match instead', readings.find((n) => n > 5), 8);
test('a findLast miss is undefined', readings.findLast((n) => n > 99), undefined);
test('a findLastIndex miss is -1', readings.findLastIndex((n) => n > 99), -1);
test('a reversed copy reports an index into the copy, not the original', reversedIndex, 1);
test('which has to be converted back', readings.length - 1 - reversedIndex, 3);
test('findLast reached the last element in one call', lastCalls, 1);
test('while find had to walk all five', firstCalls, 5);
Before findLast existed the idiom was [...xs].reverse().find(p), and the assertions show why it was a nuisance: the value is right but any index you get out of it belongs to the copy, so you must subtract it from length - 1. Forgetting that conversion is a genuinely common off-by-one.
The call counts show the other reason to prefer it. Searching from the correct end is not a style choice — on a long log where the interesting entry is recent, findLast stops immediately and find reads the whole thing.
Common mistakes
- Using an index from a reversed copy on the original. Convert it with
length - 1 - i, or usefindLastIndex. - Reversing without copying.
readings.reverse().find(...)flips your real array. Copy first with[...readings], or skip the reverse and usefindLast. - Reaching for
lastIndexOfwith a test.lastIndexOfonly matches exact values. UsefindLastIndexfor a condition.
Try it yourself
- In
['ok', 'error', 'ok', 'error', 'ok'], find the index of the last'error'two ways:lastIndexOfandfindLastIndex. - From a list of payments like
{ amount: 1200 }, find the most recent one over 1,000. - Write
findLastOld(xs, pred)using a plainforloop that counts down fromxs.length - 1.