Topic 44 of 87
Array Searching
Overview
Finding specific items or checking if they exist inside an array is a daily task.
For simple primitives (strings, numbers), indexOf and includes are perfect. But for complex arrays containing Objects, you must use modern ES6 callback methods like find() and findIndex().
Syntax
Primitive Search
javascript
const names = ["Alice", "Bob", "Charlie", "Bob"];
console.log(names.indexOf("Bob")); // 1 (Index of first match)
console.log(names.lastIndexOf("Bob")); // 3 (Index of last match)
// ES7 includes() returns a clean boolean
console.log(names.includes("Charlie")); // trueComplex Search (find & findIndex)
javascript
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
// find() returns the FIRST ELEMENT that passes the test
const match = users.find(user => user.name === "Bob");
console.log(match); // { id: 2, name: "Bob" }
// findIndex() returns the INDEX of the passing element
const idx = users.findIndex(user => user.id === 2); // 1Common Pitfalls
- Using
indexOf()to search for objects. Writingarr.indexOf({id: 1})will ALWAYS return-1(not found). This is because objects are compared by memory reference, not by their internal values. Two identical-looking objects occupy different spaces in memory. Always usefind()for objects.
Interview Questions
Q:
What does
find() return if no element matches the condition?A:
It returns undefined. (In contrast, findIndex() returns -1 if no match is found).
Real-World Example
Finding the exact product a user clicked on based on the ID in the URL.
example
javascript
const targetId = parseInt(useParams().id);
const product = inventory.find(item => item.id === targetId);Check Your Knowledge
Test your understanding of Array Searching with these quick questions.