Sub topic 9
Finding by Condition: find, findIndex, findLast, some, and filter
The previous chapter searched for a known value with indexOf and includes. Real data rarely works that way. You usually want "the first paid order" or "any user over 18", which is a condition, not a value. This chapter assumes you are comfortable with arrow functions, objects and property access, and the value-search methods from the last chapter.
The Predicate Model
A predicate is a function that takes an element and returns something truthy or falsy. Every method in this chapter calls your predicate with three arguments, (element, index, array), and walks the array from one end. Most methods stop as soon as they have an answer.
The methods differ in two ways: which direction they scan and what they return.
| Method | Scans | Returns on match | Returns if no match | Stops early |
|---|---|---|---|---|
| `find` | front to back | the element | `undefined` | yes |
| `findIndex` | front to back | the index | `-1` | yes |
| `findLast` | back to front | the element | `undefined` | yes |
| `findLastIndex` | back to front | the index | `-1` | yes |
| `some` | front to back | `true` | `false` | yes, on first truthy |
| `every` | front to back | `true` if all match | `false` | yes, on first falsy |
| `filter` | front to back | new array of all matches | `[]` | no |
findLast and findLastIndex arrived in ES2023. They let you search from the end without reversing the array or copying it.
The Methods in Action
const orders = [
{ id: 1, status: 'paid', total: 40 },
{ id: 2, status: 'pending', total: 15 },
{ id: 3, status: 'paid', total: 90 }
];
console.log(orders.find(o => o.status === 'paid').id); // 1
console.log(orders.findLast(o => o.status === 'paid').id); // 3
console.log(orders.findIndex(o => o.total > 100)); // -1
console.log(orders.some(o => o.status === 'pending')); // true
console.log(orders.filter(o => o.total > 20).length); // 2every is the counterpart of some: it asks whether all elements pass.
const totals = [40, 15, 90];
console.log(totals.every(t => t > 10)); // true
console.log(totals.every(t => t > 20)); // false
console.log([].every(t => t > 1000)); // true
console.log([].some(t => t > 0)); // falseThe last two lines are not bugs. In logic, "every element of an empty set passes" is true, and "some element passes" is false. If an empty list should fail your validation, check arr.length separately.
Choosing the Right Method
A rule of thumb: ask for the smallest answer you need. filter(...).length > 0 builds a whole array just to answer yes or no, and it never stops early. some answers the same question and stops at the first match.
Common Errors
Dereferencing a missing result
find returns undefined when nothing matches, so orders.find(...).id throws a TypeError. Use optional chaining or check the result:
const orders = [{ id: 1, status: 'paid' }];
const refunded = orders.find(o => o.status === 'refunded');
console.log(refunded?.id); // undefined, no crash
const id = refunded ? refunded.id : null;
console.log(id); // nullTreating a found falsy value as "not found"
If the array can contain 0, '', or false, then if (arr.find(...)) misreads a real match as a miss. Use findIndex and compare with -1 instead:
const scores = [5, 0, 7];
const zero = scores.find(s => s < 1);
console.log(zero ? 'found' : 'missing'); // 'missing', which is wrong
const idx = scores.findIndex(s => s < 1);
console.log(idx !== -1 ? 'found' : 'missing'); // 'found'Forgetting to return in a block body
An arrow function with braces needs an explicit return. Without it the predicate returns undefined, so nothing ever matches:
const nums = [1, 2, 3];
console.log(nums.filter(n => { n > 1; })); // []
console.log(nums.filter(n => { return n > 1; })); // [2, 3]Holes and NaN
Predicate methods test conditions, so they handle NaN without trouble: [NaN].findIndex(Number.isNaN) returns 0. They differ on sparse arrays. find and findIndex visit holes as undefined, while some, every, and filter skip them.
Exercises
Exercise
You have an array of log entries, each with a level property. Write one expression that returns the most recent entry (the one nearest the end) whose level is 'error', or undefined if there is none, without mutating or copying the array.
Show answer
logs.findLast(e => e.level === 'error'). findLast scans from the end and stops at the first match, so it needs no reverse() or copy.
Exercise
A colleague writes if (users.filter(u => u.isAdmin).length > 0). What would you change, and why?
Show answer
Replace it with users.some(u => u.isAdmin). It returns the same boolean, stops at the first admin instead of scanning the whole array, and does not allocate a new array.
Exercise
Why does [].every(x => x > 0) return true, and how would you require a non-empty array where every element is positive?
Show answer
every is vacuously true for an empty array because no element fails the predicate. Use arr.length > 0 && arr.every(x => x > 0).