JavaScript Array Search Methods
Array indexOf()
The indexOf() method searches an array for a specific element and returns its first occurrence index. If the element is not found, it returns -1.
Example
Search for the position of "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple"); // 0
Syntax
array.indexOf(item, start)
- item: Required. The item to search for.
- start: Optional. The position to start the search. Negative values start from the end.
Array lastIndexOf()
The lastIndexOf() method searches an array for a specific element and returns its last occurrence index. If the element is not found, it returns -1.
Example
Search for the last position of "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];let position = fruits.lastIndexOf("Apple"); // 2
Syntax
array.lastIndexOf(item, start)
- item: Required. The item to search for.
- start: Optional. The position to start the search. Negative values start from the end.
Array includes()
The includes() method checks if an array contains a specified element, returning true or false.
Example
Check if "Mango" is in the array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];let hasMango = fruits.includes("Mango"); // true
Syntax
array.includes(item)
- item: Required. The item to search for.
Array find()
The find() method returns the value of the first element that passes a provided test function.
Example
Find the first number greater than 18:
const numbers = [4, 9, 16, 25, 29];let first = numbers.find(value => value > 18); // 25
Array findIndex()
The findIndex() method returns the index of the first element that passes a provided test function.
Example
Find the index of the first number greater than 18:
const numbers = [4, 9, 16, 25, 29];let index = numbers.findIndex(value => value > 18); // 3
Array findLast()
The findLast() method returns the value of the last element that satisfies a provided test function, starting from the end of the array.
Example
Find the last temperature greater than 40:
const temps = [27, 28, 30, 40, 42, 35, 30];let high = temps.findLast(temp => temp > 40); // 42
Array findLastIndex()
The findLastIndex() method returns the index of the last element that satisfies a provided test function, starting from the end of the array.
Example
Find the index of the last temperature greater than 40:
const temps = [27, 28, 30, 40, 42, 35, 30];let index = temps.findLastIndex(temp => temp > 40); // 4
Browser Support
- indexOf(): Supported in all modern browsers.
- lastIndexOf(): Supported in all modern browsers.
- includes(): Supported in modern browsers since March 2017.
- find() and findIndex(): Supported in modern browsers since June 2017.
- findLast() and findLastIndex(): Supported in modern browsers since July 2023.