Sub topic 9
Finding by Condition: find, findIndex, findLast, some, and filter
The earlier chapter on indexOf, lastIndexOf, and includes covered searching for a known value. Real searches are usually less exact. You want "the first paid order", "any user without an email", or "every product under $20". Those questions are conditions, not values. JavaScript answers them with a family of predicate methods.
This chapter assumes you know arrow functions, array indexing, object property access, and truthy versus falsy values. It also assumes you have read the chapter on value search, because it refers back to includes and indexOf.
The Predicate Model
A predicate is a function that takes an element and returns something JavaScript treats as true or false. Every method in this chapter calls your predicate with the same three arguments:
element: the current item.index: its position.array: the array being searched.
Each method also accepts an optional second argument, thisArg, which sets this inside a regular (non-arrow) predicate. You will rarely need it with arrow functions.
The methods differ in two ways: what they return, and whether they stop early.
| Method | Returns on match | Returns on no match | Stops early? | Direction |
|---|---|---|---|---|
| `find` | first matching element | `undefined` | yes | start to end |
| `findIndex` | index of first match | `-1` | yes | start to end |
| `findLast` | last matching element | `undefined` | yes | end to start |
| `findLastIndex` | index of last match | `-1` | yes | end to start |
| `some` | `true` | `false` | yes, on first truthy | start to end |
| `every` | `true` if all match | `false` | yes, on first falsy | start to end |
| `filter` | new array of all matches | `[]` | no | start to end |
findLast and findLastIndex arrived in ES2023. They are available in all current browsers and in Node.js 18 and later.
A Worked Example
Here is one dataset queried with each method:
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); // 2Each line asks a different question:
findasks "give me the first paid order". It returns the object itself, not a copy, so you can read or change its properties.findLastasks "give me the most recent paid order", assuming the array is in chronological order.findIndexasks "where is the first order over 100?" None exists, so it returns-1.someasks "is anything pending?" It needs a yes or no, not the element.filterasks "which orders exceed 20?" It collects every match.
Choosing the Right Method
Decide by the shape of the answer you need.
find and findIndex
Use find when you want the element and expect at most one, or only care about the first. Use findIndex when you need the position, for example to replace or remove the element:
const tasks = [
{ id: 'a', done: false },
{ id: 'b', done: true },
{ id: 'c', done: false }
];
const i = tasks.findIndex(t => t.id === 'b');
if (i !== -1) {
tasks.splice(i, 1); // remove task 'b' in place
}
console.log(tasks.map(t => t.id)); // ['a', 'c']Always check for -1 before using the index. Passing -1 to splice removes the last element, which is a silent and nasty bug.
findLast and findLastIndex
These scan from the end. They are the right tool when the array is ordered by time and you want the latest match. Before ES2023, people wrote [...arr].reverse().find(...). That copies the whole array and then reverses it. It also makes findIndex return a reversed position you have to convert back. findLast avoids both.
const log = [
{ level: 'info', msg: 'start' },
{ level: 'error', msg: 'disk full' },
{ level: 'info', msg: 'retry' },
{ level: 'error', msg: 'timeout' }
];
console.log(log.findLast(e => e.level === 'error').msg); // 'timeout'
console.log(log.findLastIndex(e => e.level === 'error')); // 3some and every
some returns true as soon as one element passes. every returns false as soon as one element fails. Both are boolean questions, so use them in if conditions and validation:
const cart = [
{ name: 'pen', price: 2, inStock: true },
{ name: 'lamp', price: 35, inStock: false }
];
const canCheckout = cart.every(item => item.inStock);
const hasExpensive = cart.some(item => item.price > 30);
console.log(canCheckout); // false
console.log(hasExpensive); // trueThe two methods are logical mirrors. arr.every(p) gives the same result as !arr.some(x => !p(x)).
some versus includes
Both return a boolean. Use includes when you have an exact value to compare, and some when you have a condition. includes cannot look inside objects, because it compares object references:
const users = [{ name: 'Ana' }, { name: 'Bo' }];
console.log(users.includes({ name: 'Ana' })); // false, different object
console.log(users.some(u => u.name === 'Ana')); // truefilter
filter always visits every element and returns a new array. The new array is a shallow copy. It contains the same object references as the original, so changing a filtered object changes the original object too:
const items = [{ qty: 0 }, { qty: 4 }];
const available = items.filter(i => i.qty > 0);
available[0].qty = 99;
console.log(items[1].qty); // 99, same object
console.log(available === items); // false, different arrayfilter does not mutate the source array. It returns a new one even when every element passes.
Short-Circuiting and Cost
Every method here runs in O(n) time in the worst case. In practice they behave differently. find, findIndex, some, and every stop as soon as the answer is known. filter always walks the whole array.
You can watch this happen by counting predicate calls:
const nums = [3, 8, 12, 5, 20];
let calls = 0;
nums.some(n => { calls++; return n > 10; });
console.log(calls); // 3
calls = 0;
nums.filter(n => { calls++; return n > 10; });
console.log(calls); // 5The cost matters most when the predicate is expensive or the array is large. A common anti-pattern makes the point:
const people = [{ age: 15 }, { age: 22 }, { age: 40 }];
const firstAdultSlow = people.filter(p => p.age >= 18)[0]; // scans everything
const firstAdultFast = people.find(p => p.age >= 18); // stops at index 1
console.log(firstAdultSlow === firstAdultFast); // trueThe same applies to filter(...).length > 0, which should be some(...). Both forms give the right answer, but the filter version does extra work and builds an array it throws away.
If you run the same search many times over large data, linear predicate scans add up. The final chapter covers binary search and Set/Map lookups for that case.
Common Errors
Forgetting to return
An arrow function with a braced body needs an explicit return. Without it, the predicate returns undefined, which is falsy, so nothing ever matches:
const scores = [55, 80, 92];
const broken = scores.filter(s => { s > 70 });
const fixed = scores.filter(s => s > 70);
console.log(broken); // []
console.log(fixed); // [80, 92]Truthiness surprises
The methods test the predicate's result for truthiness, not strict true. If the predicate returns 0, '', NaN, or null, the element fails. This bites when you return a property directly:
const stock = [{ sku: 'A', qty: 0 }, { sku: 'B', qty: 3 }];
console.log(stock.filter(s => s.qty).map(s => s.sku)); // ['B']
console.log(stock.filter(s => s.qty !== undefined).map(s => s.sku)); // ['A', 'B']The first line may be what you want, but write s.qty > 0 so the intent is explicit. The same issue affects the idiom arr.filter(Boolean). It removes null and undefined, but it also removes 0, '', and false. Many arrays contain those as legitimate values.
Treating undefined from find as "not found"
find returns undefined both when nothing matches and when the matching element is itself undefined. If the array can contain undefined, use findIndex and compare against -1:
const slots = [null, undefined, 'x'];
console.log(slots.find(v => v === undefined)); // undefined (ambiguous)
console.log(slots.findIndex(v => v === undefined)); // 1 (unambiguous)For arrays of objects this is rarely a problem, and find with optional chaining reads well: orders.find(o => o.id === 7)?.total.
Async predicates
A predicate must return its answer synchronously. An async function returns a Promise, and every Promise is truthy, so every element passes:
const ids = [1, 2, 3];
const wrong = ids.filter(async id => id > 2);
console.log(wrong.length); // 3
async function filterAsync(arr, predicate) {
const results = await Promise.all(arr.map(predicate));
return arr.filter((_, i) => results[i]);
}
filterAsync(ids, async id => id > 2).then(r => console.log(r)); // [3]Edge Cases
Sparse arrays
Sparse arrays (arrays with holes) expose a split in the family. The find family visits holes and passes undefined for them. some, every, and filter skip holes entirely:
const sparse = [1, , 3];
console.log(sparse.findIndex(x => x === undefined)); // 1
console.log(sparse.some(x => x === undefined)); // false
console.log(sparse.filter(x => x === undefined).length); // 0
console.log(sparse.every(x => x !== undefined)); // trueHoles are uncommon in practice, but they appear with new Array(n) or delete arr[i]. Fill or compact such arrays before searching them.
Mutating during iteration
The methods read the array's length once, before the first callback. Elements appended during the search are not visited. Elements changed before the search reaches them are seen with their new values:
const queue = [1, 2, 3];
const seen = [];
queue.filter(n => {
seen.push(n);
if (n === 1) {
queue.push(4); // not visited: past the original length
queue[2] = 30; // visited with the new value
}
return true;
});
console.log(seen); // [1, 2, 30]The behavior is defined, but code that relies on it is hard to read. Keep predicates free of side effects.
Using index and array arguments
The second and third arguments let a predicate compare against neighbors. A classic use is finding where a sequence stops being sorted:
const readings = [1, 4, 7, 6, 9];
const breakAt = readings.findIndex((v, i, arr) => i > 0 && v < arr[i - 1]);
console.log(breakAt); // 3The same pattern with filter removes duplicates, arr.filter((v, i, a) => a.indexOf(v) === i). Each indexOf call is itself a scan, so that version is O(n²), and [...new Set(arr)] is the faster choice for large arrays.
Exercises
Exercise
You have an array events sorted oldest to newest. Write one expression that returns the message of the most recent event whose level is 'warn', or undefined if none exists, without throwing.
Show answer
events.findLast(e => e.level === 'warn')?.msg — findLast scans from the end and stops at the first match, and optional chaining returns undefined instead of throwing when no event matches.
Exercise
A teammate writes if (users.filter(u => u.banned).length > 0) { ... }. What is wrong with it, and what should it be?
Show answer
It gives the correct result but scans the whole array and builds a throwaway array. Use users.some(u => u.banned), which returns a boolean and stops at the first banned user.
Exercise
What does [].every(x => x > 100) return, and why can that be a problem in form validation?
Show answer
It returns true, because no element fails the condition (vacuous truth). An empty list of fields or items passes validation, so check the length separately if empty input should be rejected.
Exercise
Why does [0, 1, 2].filter(n => { n >= 1 }) return an empty array, and how do you fix it?
Show answer
The braced arrow body has no return statement, so the predicate returns undefined (falsy) for every element. Write n => n >= 1 or add return n >= 1; inside the braces.