Array Search Methods are built-in JavaScript methods used to search for elements in an array. They help us check whether an element exists, find its position (index), or retrieve elements that satisfy a condition.
1. indexOf()
Returns the first index of the specified element. If the element is not found, it returns -1.
Syntax:
array.indexOf(element)
Example:
const fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.indexOf("Banana"));
Output:
1
2. lastIndexOf()
Returns the last index of the specified element. If not found, it returns -1.
Example:
const fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.lastIndexOf("Banana"));
Output:
3
3. includes()
Checks whether an element exists in an array. It returns true or false.
Example:
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Mango"));
console.log(fruits.includes("Orange"));
Output:
true
false
4. find()
Returns the first element that satisfies the given condition. If no element matches, it returns undefined.
Example:
const numbers = [5, 12, 8, 20];
const result = numbers.find(num => num > 10);
console.log(result);
Output:
12
Explanation
- 5 > 10 (Wrong)
- 12 > 10 → Stops and returns 12 (correct)
5. findIndex()
Returns the index of the first element that satisfies the condition. If none match, it returns -1.
Example:
const numbers = [5, 12, 8, 20];
const index = numbers.findIndex(num => num > 10);
console.log(index);
Output:
1
6. findLast()
Returns the last element that satisfies the given condition.
Example:
const numbers = [5, 12, 8, 20];
const result = numbers.findLast(num => num > 10);
console.log(result);
Output:
20
Explanation
Search starts from the end:
- 20 > 10 → Returns 20
7. findLastIndex()
Returns the index of the last element that satisfies the condition.
Example:
const numbers = [5, 12, 8, 20];
const index = numbers.findLastIndex(num => num > 10);
console.log(index);
Output:
3
Easy Way to Remember
- indexOf() → First index of a value.
- lastIndexOf() → Last index of a value.
- includes() → Checks if a value exists.
- find() → First element matching a condition.
- findIndex() → Index of the first matching element.
- findLast() → Last element matching a condition.
- findLastIndex() → Index of the last matching element.
Top comments (0)