Searching arrays in JavaScript can be done using index lookups (indexOf, includes) or condition-based predicate functions (find, findIndex, findLastIndex).
flowchart TD
SearchReq["Search Array"] --> SimpleCheck{"Searching primitive value or complex object?"}
SimpleCheck -- "Primitive (Value Check)" --> Exists{"Check Existence or Index?"}
Exists -- "Boolean Existence" --> Inc["includes(val)"]
Exists -- "Index Position" --> Idx["indexOf(val)"]
SimpleCheck -- "Complex Object / Custom Rule" --> Rule{"Need Item or Index?"}
Rule -- "Found Item Object" --> Find["find(predicate)"]
Rule -- "Index Position" --> FindIdx["findIndex(predicate)"]
| Method | Return Type | Accepts Callback Predicate? | Stops at First Match? |
|---|---|---|---|
includes(val) |
boolean |
No | Yes |
indexOf(val) |
number (-1 if missing) |
No | Yes |
find(predicate) |
Item / undefined |
Yes | Yes |
findIndex(predicate) |
number (-1 if missing) |
Yes | Yes |
findLastIndex(predicate) |
number (-1 if missing) |
Yes (Searches backwards) | Yes |
// Demonstrating Array searching methods
// 1. Primitive Value Lookups
const roles = ["guest", "editor", "admin", "publisher"];
console.log(`Has 'admin' role? ${roles.includes("admin")}`); // true
console.log(`Index of 'editor': ${roles.indexOf("editor")}`); // 1
// 2. Object Array Searching with find() and findIndex()
const users = [
{ id: 101, name: "Alex", active: false },
{ id: 102, name: "Maksudur", active: true },
{ id: 103, name: "Sarah", active: true }
];
// Find first active user object
const firstActiveUser = users.find((user) => user.active);
console.log("First Active User Found:", firstActiveUser); // { id: 102, name: "Maksudur", active: true }
// Find index of user with id 103
const targetIndex = users.findIndex((user) => user.id === 103);
console.log(`Index of User 103: ${targetIndex}`); // 2
// Find last active user (ES2023 findLastIndex)
const lastActiveIndex = users.findLastIndex((user) => user.active);
console.log(`Last Active User Index: ${lastActiveIndex}`); // 2
find() for Objects: indexOf() uses strict equality (===) and will fail when searching for object references that do not share the same memory pointer. Use find() with a predicate function instead.includes() Handles NaN Correctly: [NaN].includes(NaN) returns true, whereas [NaN].indexOf(NaN) returns -1.find() and findIndex() stop searching immediately upon finding the first element that satisfies the condition.Given an array of products [{id: 1, price: 50}, {id: 2, price: 150}], write a find() call that returns the first product with a price greater than 100.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.