JavaScript provides several methods to search through an array. Some methods allow you to look for a specific value, while others allow you to find items that match a certain condition.
These methods are used when you have a specific value in mind (like a number or string) and you want to know if or where it exists in the array.
Returns the position of the first (or last) occurrence of a value. Returns -1
if the value is not found.
const fruits = ["Apple", "Orange", "Apple", "Mango"];
console.log(fruits.indexOf("Apple")); // 0
console.log(fruits.lastIndexOf("Apple")); // 2
Returns true if the array contains the specified value, false
otherwise. This is often cleaner than checking indexOf !== -1.
const colors = ["Red", "Green", "Blue"];
console.log(colors.includes("Green")); // true
Sometimes you need to find an item not by its value, but by a test. For example, finding the first number greater than 10.
The find() method returns the value of the first array
element that passes a test function.
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value) {
return value > 18;
}
console.log(first); // 25
Similar to find(), but returns the index of the first element
that passes the test, instead of its value.
const numbers = [4, 9, 16, 25, 29];
let index = numbers.findIndex(x => x > 18); // Using arrow function
console.log(index); // 3
Newer versions of JavaScript introduced methods to search an array starting from the end:
findLast() — Returns the value of the last matching element.findLastIndex() — Returns the index of the last matching element.indexOf() if you need the position of a primitive valueincludes() to simply check for existencefind() when looking for an object or matching a
conditionfind receives three arguments: value, index,
and the array itself