Array.lastIndexOf()
The Array.lastIndexOf() method in JavaScript is used to find the last occurrence of a specified element in an array. It searches the array backward, starting at a specified index or the array’s end by default. If the element is not found, it returns -1.
Syntax
</>
Copy
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
Parameters
| Parameter | Description |
|---|---|
searchElement | The element to locate in the array. |
fromIndex (optional) | The index at which to start searching backward. Defaults to array.length - 1. If negative, it is taken as an offset from the end of the array. |
Return Value
The lastIndexOf() method returns the last index at which the searchElement is found in the array. If the element is not found, it returns -1.
Examples
1. Finding the Last Occurrence of an Element
In this example, the method is used to locate the last occurrence of an element in the array.
</>
Copy
const fruits = ['apple', 'banana', 'cherry', 'apple', 'banana'];
console.log(fruits.lastIndexOf('banana'));
console.log(fruits.lastIndexOf('apple'));
Output
4
3
fruits.lastIndexOf('banana')finds the last occurrence of'banana'at index4.fruits.lastIndexOf('apple')finds the last occurrence of'apple'at index3.
2. Using the fromIndex Parameter
The fromIndex parameter specifies the index at which to start searching backward.
</>
Copy
const numbers = [1, 2, 3, 2, 1];
console.log(numbers.lastIndexOf(2, 3));
console.log(numbers.lastIndexOf(2, 1));
Output
3
1
numbers.lastIndexOf(2, 3)searches backward from index3and finds the last occurrence of2at index3.numbers.lastIndexOf(2, 1)searches backward from index1and finds the last occurrence of2at index1.
3. Negative fromIndex Value
A negative fromIndex value is treated as an offset from the end of the array.
</>
Copy
const colors = ['red', 'blue', 'green', 'blue'];
console.log(colors.lastIndexOf('blue', -2));
console.log(colors.lastIndexOf('red', -1));
Output
1
0
colors.lastIndexOf('blue', -2)starts searching backward from index2(offset from the end) and finds'blue'at index1.colors.lastIndexOf('red', -1)searches backward from the last element and finds'red'at index0.
4. Element Not Found
If the element is not found in the array, lastIndexOf() returns -1.
</>
Copy
const animals = ['cat', 'dog', 'bird'];
console.log(animals.lastIndexOf('fish'));
console.log(animals.lastIndexOf('dog', -3));
Output
-1
-1
animals.lastIndexOf('fish')returns-1because'fish'is not in the array.animals.lastIndexOf('dog', -3)returns-1because'dog'is not found when searching backward from the specified index.
