Searching Arrays
Searching an array means answering one of three questions: is a value in the array, where is it, or which item matches a condition. JavaScript has a method for each, and two more (some and every) that test the whole array at once. They replace most hand-written search loops, stop as soon as they have an answer, and make the question obvious from the method's name.
In One Minute
- Is it there?
includes(value)returnstrueorfalse, and handlesNaNcorrectly. - Where is it?
indexOf(value)andlastIndexOf(value)return a position or-1. - Which item matches a test?
find(fn)returns the first matching item (orundefined);findLast(fn)searches from the end. - Where is the matching item?
findIndex(fn)andfindLastIndex(fn)return a position or-1. - Does any / every item pass?
some(fn)andevery(fn)return booleans.
Method Table
| Method | Description | Returns when nothing matches |
|---|---|---|
includes(value, from) | It is used to check whether value is in the array (uses SameValueZero). | false |
indexOf(value, from) | It is used to find the first index of value (uses ===). | -1 |
lastIndexOf(value, from) | It is used to find the last index of value. | -1 |
find(fn) | It is used to get the first item for which fn returns truthy. | undefined |
findIndex(fn) | It is used to get the index of the first matching item. | -1 |
findLast(fn) | It is used to get the last matching item (ES2023). | undefined |
findLastIndex(fn) | It is used to get the index of the last matching item (ES2023). | -1 |
some(fn) | It is used to check whether at least one item matches. | false |
every(fn) | It is used to check whether all items match. | true (for an empty array) |
The callback fn receives (item, index, array) and should return true for a match.
Searching for a Value
const grades = [9, 10, 11, 10, 12];
console.log(grades.includes(11));
console.log(grades.includes(8));
console.log(grades.indexOf(10));
console.log(grades.lastIndexOf(10));
console.log(grades.indexOf(8));
console.log(grades.includes(10, 4));true
false
1
3
-1
falseThe optional second argument says where to start: includes(10, 4) only looks from index 4.
includes vs indexOf
Use includes for yes-or-no questions. Besides reading more clearly, it handles NaN, which indexOf can't find because NaN !== NaN:
const readings = [1, NaN, 3];
console.log(readings.indexOf(NaN));
console.log(readings.includes(NaN));-1
trueBoth compare values like ===: they find primitives by value but objects only by reference. [{ id: 1 }].includes({ id: 1 }) is false, because the object in the call is a different object. To find objects by their contents, use find.
Searching with a Condition
find and findIndex take a function that tests each item, and stop at the first item that passes:
const payments = [
{ id: 1, name: "Navika", amount: 120, paid: true },
{ id: 2, name: "Srihitha", amount: 85, paid: false },
{ id: 3, name: "Advitha", amount: 45, paid: false },
];
const firstUnpaid = payments.find((p) => !p.paid);
console.log(firstUnpaid);
console.log(payments.findIndex((p) => p.name === "Advitha"));
console.log(payments.find((p) => p.amount > 500));
const lastUnpaid = payments.findLast((p) => !p.paid);
console.log(lastUnpaid.name, payments.findLastIndex((p) => p.paid));{ id: 2, name: 'Srihitha', amount: 85, paid: false }
2
undefined
Advitha 0Explanation: find returns the item itself, not a copy, so changing the result changes the object in the array. When nothing passes, find gives undefined and findIndex gives -1. findLast and findLastIndex search from the end, which is handy for "the most recent" when items are in date order.
Testing the Whole Array: some and every
const amounts = [120, 85, 45];
console.log(amounts.some((a) => a > 100));
console.log(amounts.every((a) => a > 0));
console.log(amounts.every((a) => a > 50));
console.log([].some((a) => a > 0));
console.log([].every((a) => a > 0));true
true
false
false
trueExplanation: some stops at the first true; every stops at the first false. On an empty array, some is false (no item passes) and every is true (no item fails). That second result is logically correct (it is called vacuous truth) but surprises people: "every payment is valid" is true when there are no payments.
Searching Is Linear
All of these methods look at items one by one, from the start (or end). For a list of 10 or 10,000 items that is fast. But searching inside a loop multiplies the work:
const students = [
{ id: "s1", name: "Navika" },
{ id: "s2", name: "Srihitha" },
{ id: "s3", name: "Advitha" },
];
const payments = [{ studentId: "s3", amount: 45 }, { studentId: "s1", amount: 120 }];
// find inside map: searches the students list once per payment
console.log(payments.map((p) => students.find((s) => s.id === p.studentId).name));
// build a lookup once, then each search is instant
const byId = new Map(students.map((s) => [s.id, s]));
console.log(payments.map((p) => byId.get(p.studentId).name));['Advitha', 'Navika']
['Advitha', 'Navika']For a few hundred items, either is fine. For thousands of payments and thousands of students, the Map version is dramatically faster. Map has its own lesson in the Sets and Maps chapter.
In Practice
The Fee Tracker validates a batch of payments before saving: every amount must be positive, no student may appear twice, and it reports the first problem it finds:
function validateBatch(batch) {
if (batch.length === 0) return "The batch is empty.";
const bad = batch.find((p) => !(p.amount > 0));
if (bad) return `Invalid amount for ${bad.name}: ${bad.amount}`;
const duplicate = batch.find((p, i) => batch.findIndex((q) => q.name === p.name) !== i);
if (duplicate) return `${duplicate.name} appears more than once.`;
return batch.every((p) => typeof p.name === "string") ? "OK" : "Missing a name.";
}
console.log(validateBatch([{ name: "Navika", amount: 120 }, { name: "Advitha", amount: 45 }]));
console.log(validateBatch([{ name: "Navika", amount: 120 }, { name: "Srihitha", amount: -5 }]));
console.log(validateBatch([{ name: "Navika", amount: 1 }, { name: "Navika", amount: 2 }]));
console.log(validateBatch([]));OK
Invalid amount for Srihitha: -5
Navika appears more than once.
The batch is empty.The duplicate check works because findIndex returns the first index of a name; if that isn't the current index, the name appeared earlier.
Common Mistakes
if (list.indexOf(x)). False when x is at index 0, true when it's missing (-1). Use includes.
Searching for an object with includes. It compares references. Use find with a condition on its properties.
Forgetting find can return undefined. list.find(...).name throws when nothing matches. Use list.find(...)?.name.
Trusting every on an empty array. It returns true. Check the length when that matters.
Practice
Challenge: Given a list of payments in date order, write latestPaymentFor(payments, name) that returns the most recent payment's amount for that student, or 0 if they never paid.
Show solution
function latestPaymentFor(payments, name) {
return payments.findLast((p) => p.name === name)?.amount ?? 0;
}
const payments = [
{ name: "Navika", amount: 120 },
{ name: "Advitha", amount: 45 },
{ name: "Navika", amount: 60 },
];
console.log(latestPaymentFor(payments, "Navika"));
console.log(latestPaymentFor(payments, "Srihitha"));60
0Key Takeaways
| Question | Method |
|---|---|
| Is the value present? | arr.includes(v) |
| Position of a value | arr.indexOf(v) |
| First item matching a test | arr.find(fn) |
| Last item matching a test | arr.findLast(fn) |
| Any match? All match? | arr.some(fn), arr.every(fn) |
Was this tutorial helpful?