The indexOf and lastIndexOf methods are built-in functions in JavaScript used to find the position of a specified element within an array.
The indexOf and lastIndexOf methods in JavaScript are used to search for a particular element in an array and return its position (index) within the array. The indexOf method searches for the first occurrence of the specified element, while lastIndexOf searches for the last occurrence. If the element is not found, both methods return -1.
array.indexOf(searchElement[, fromIndex])
array.lastIndexOf(searchElement[, fromIndex])
- Both indexOf and lastIndexOf take two arguments: the element you want to find and an optional parameter called fromIndex (which specifies the index at which to start the search).
- indexOf searches for the element from the beginning of the array and returns the first index at which it finds a match.
- lastIndexOf searches for the element from the end of the array and returns the last index at which it finds a match.
- If the element is not found, both methods return -1.
- If fromIndex is provided, the search starts from that index. For lastIndexOf, the search is performed backwards from fromIndex.
Remember that both methods return the index of the first occurrence they find, even if there are multiple occurrences of the same element.
Using indexOf
const fruits = [ 'apple', 'banana', 'cherry', 'apple', 'cherry' ]; const index = fruits.indexOf('cherry'); console.log(index); // Output: 2
In this example, we have an array fruits containing different fruits. We use indexOf to find the first occurrence of 'cherry' in the array. The method returns 2 because 'cherry' is found at index 2.
Using lastIndexOf
const fruits = ['apple', 'banana', 'cherry', 'apple', 'cherry']; const lastIndex = fruits.lastIndexOf('cherry'); console.log(lastIndex); // Output: 4
Here, we use lastIndexOf to find the last occurrence of 'cherry' in the array. The method returns 4 because the last occurrence of 'cherry' is at index 4.
Handling non-existent elements:
If the element is not found in the array, indexOf returns -1 indicating that the element is not present.
const fruits = ['apple', 'banana', 'cherry']; const index = fruits.indexOf('grape'); console.log(index); // Output: -1
Searching from a specific index:
In this case, we start searching for 'apple' starting from index 1. The method returns 3 because the first occurrence of 'apple' after index 1 is at index 3.
const fruits = ['apple', 'banana', 'cherry', 'apple', 'cherry']; const index = fruits.indexOf('apple', 1); console.log(index); // Output: 3
Using lastIndexOf with a specified fromIndex
Here, we use lastIndexOf to find the last occurrence of 'apple' before index 3. The method returns 0 because the last occurrence of 'apple' before index 3 is at index 0.
const fruits = ['apple', 'banana', 'cherry', 'apple', 'cherry']; const lastIndex = fruits.lastIndexOf('apple', 3); console.log(lastIndex); // Output: 0