Array Methods: find, findIndex, includes, indexOf
Search methods help you locate specific items in arrays. find returns the first matching element, findIndex returns its position, includes checks if a value exists, and indexOf returns the index of a value.
Search Methods
- find(callback) — Returns the FIRST element where callback returns true. Returns undefined if not found
- findIndex(callback) — Returns the INDEX of the first match. Returns -1 if not found
- includes(value) — Returns true/false. Simple 'does it exist?' check
- indexOf(value) — Returns the index of value, or -1 if not found. Uses === for comparison
- some(callback) — Returns true if ANY element passes the test
- every(callback) — Returns true if ALL elements pass the test
Search Methods Code
const users = [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Charlie", age: 28 },
];
// find — get the first matching object
const bob = users.find(u => u.name === "Bob");
console.log(bob); // { id: 2, name: "Bob", age: 30 }
const notFound = users.find(u => u.name === "Dave");
console.log(notFound); // undefined
// findIndex — get the position
const bobIndex = users.findIndex(u => u.name === "Bob");
console.log(bobIndex); // 1
// includes — simple existence check
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.includes("Banana")); // true
console.log(fruits.includes("Grape")); // false
// indexOf — get position of simple value
console.log(fruits.indexOf("Cherry")); // 2
console.log(fruits.indexOf("Grape")); // -1
// some — does ANY match?
const hasAdult = users.some(u => u.age >= 18);
console.log(hasAdult); // true
// every — do ALL match?
const allAdults = users.every(u => u.age >= 18);
console.log(allAdults); // trueTip
Tip
Use optional chaining with find for safe access: const city = users.find(u => u.id === 5)?.address?.city ?? 'Unknown'. This prevents crashes when the user isn't found or address is missing.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Using indexOf to search for objects doesn't work — it uses reference equality. indexOf({name: 'Alice'}) returns -1 even if the array contains an identical object. Use findIndex with a callback for object searches.
Practice Task
Note
Search operations: (1) Use find to locate a user by ID in an array of user objects. (2) Use includes to check if a tag exists in a tags array. (3) Use some to check if any user is an admin. (4) Use every to verify all prices are positive.
Quick Quiz
Key Takeaways
- Search methods help you locate specific items in arrays.
- find(callback) — Returns the FIRST element where callback returns true. Returns undefined if not found
- findIndex(callback) — Returns the INDEX of the first match. Returns -1 if not found
- includes(value) — Returns true/false. Simple 'does it exist?' check