JavaScript Arrays Searching
Searching is one of the most common operations performed on arrays. JavaScript provides several built-in methods that help you find elements, check if an element exists, or get the position of an element.
Instead of writing long loops, you can use these methods to search arrays quickly and easily.
indexOf()
The indexOf() method returns the index of the first matching element.
If the value is not found, it returns -1.
Syntax
arrayName.indexOf(value)
Example
let fruits = ["Apple", "Banana", "Mango", "Orange"];
console.log(fruits.indexOf("Mango"));Output
2
Value Not Found
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.indexOf("Grapes"));Output
-1
lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a value.
Syntax
arrayName.lastIndexOf(value)
Example
let numbers = [10, 20, 30, 20, 40];
console.log(numbers.lastIndexOf(20));Output
3
includes()
The includes() method checks whether an element exists in an array.
It returns either true or false.
Syntax
arrayName.includes(value)
Example
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana"));Output
true
Element Does Not Exist
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Orange"));Output
false
find()
The find() method returns the first element that satisfies a condition.
If no element matches, it returns undefined.
Syntax
arrayName.find(function(element) {
return condition;
});Example
let numbers = [5, 12, 18, 25];
let result = numbers.find(function(num) {
return num > 10;
});
console.log(result);Output
12
findIndex()
The findIndex() method returns the index of the first element that matches a condition.
If no element matches, it returns -1.
Syntax
arrayName.findIndex(function(element) {
return condition;
});Example
let numbers = [5, 12, 18, 25];
let result = numbers.findIndex(function(num) {
return num > 10;
});
console.log(result);Output
1
Important Points
- indexOf() returns the first matching index.
- lastIndexOf() returns the last matching index.
- includes() returns true or false.
- find() returns the first matching element.
- findIndex() returns the index of the first matching element.
- If nothing is found, indexOf() and findIndex() return -1, while find() returns undefined.
Comparison
| Method | Returns | Not Found |
| indexOf() | First matching index | -1 |
| lastIndexOf() | Last matching index | -1 |
| includes() | true or false | false |
| find() | First matching element | undefined |
| findIndex() | First matching index | -1 |
Example
let students = ["Rahul", "Aman", "Priya", "Neha"];
console.log(students.includes("Priya"));
console.log(students.indexOf("Neha"));
console.log(students.indexOf("Rohit"));Output
true
3
-1