Member-only story
Here’s a detailed guide covering JavaScript array search techniques, from simple to advanced:
Not a Medium member? Read this article here
1. Basic Search with indexOf()
The indexOf()
method returns the first index of the specified element, or -1
if it’s not found.
Example:
const fruits = ['apple', 'banana', 'cherry'];
const index = fruits.indexOf('banana');
console.log(index); // 1
Use Case: Works well for finding the position of simple values (strings, numbers) in an array.
2. Check Existence with includes()
The includes()
method checks if an array contains a specific element, returning true
or false
.
Example:
const colors = ['red', 'green', 'blue'];
console.log(colors.includes('green')); // true
Use Case: Great for checking if an element exists without caring about its index.
3. Finding Elements with find()
The find()
method returns the first element that satisfies a provided condition.
Example:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]…