Combining at() with findLastIndex()
What you'll learn: How to use findLastIndex() to locate positions from the end of an array, then efficiently access those elements with at().
The Perfect Pairing
When you find the index of an element from the end of an array using findLastIndex(), you often need to access that element (or nearby elements). The at() method is the ideal companion because both methods work naturally with negative indices and end-of-array operations.
Why These Methods Work Well Together
findLastIndex() searches backward and returns a regular positive index (or -1 if not found). You can then use at() to:
- Access the found element directly
- Check adjacent elements using offset calculations
- Work with negative indices relative to that position
Practical Patterns
Finding and accessing the last match:
const scores = [50, 75, 90, 85, 90, 60];
const lastHighScoreIdx = scores.findLastIndex(s => s >= 90);
// Access the element
const highScore = scores.at(lastHighScoreIdx); // 90
// Check the previous element
const beforeHighScore = scores.at(lastHighScoreIdx - 1); // 85
Working with context around the match:
const logs = ['INFO', 'WARN', 'ERROR', 'INFO', 'DEBUG'];
const lastErrorIdx = logs.findLastIndex(log => log === 'ERROR');
// Get elements around the error
const errorLog = logs.at(lastErrorIdx); // 'ERROR'
const nextLog = logs.at(lastErrorIdx + 1); // 'INFO'
const prevLog = logs.at(lastErrorIdx - 1); // 'WARN'
The combination shines when you need context: findLastIndex() gives you the anchor point, and at() lets you explore around it without bounds-checking headaches.
Key Takeaway: Use findLastIndex() to locate positions from the end, then leverage at() to access that element and its neighbors—this pattern is cleaner and more expressive than traditional bracket notation with length calculations.