The lastIndexOf() method of the Array class in JavaScript returns the last (greatest) index at which a given element can be found in the calling array. If the element is not found, it returns -1.
There are 2 variations for the syntax of Array.lastIndexOf() method. They are:
lastIndexOf(searchElement)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
This method returns the last (greatest) index at which a given element can be found in the calling array, starting the search at the end of the array.
Returns value of type Number
.
lastIndexOf(searchElement, fromIndex)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
fromIndex | optional | The index at which to start searching backwards. Defaults to the array's length minus one. |
This method returns the last (greatest) index at which a given element can be found in the calling array, starting the search at the specified fromIndex.
Returns value of type Number
.
In JavaScript, we can use the lastIndexOf() method to find the last occurrence of a specified element in an array.
For example,
const arr = [1, 2, 3, 4, 3, 2, 1];
const lastIndexOfTwo = arr.lastIndexOf(2);
console.log(lastIndexOfTwo);
5
We can use the lastIndexOf() method to find the last occurrence of a specified element in an array, starting the search from a specific index.
For example,
const arr = [1, 2, 3, 4, 3, 2, 1];
const lastIndexOfThreeFromIndex4 = arr.lastIndexOf(3, 4);
console.log(lastIndexOfThreeFromIndex4);
4
We can use the lastIndexOf() method to find the last occurrence of a specified string in an array.
For example,
const strArr = ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry'];
const lastIndexOfBanana = strArr.lastIndexOf('banana');
console.log(lastIndexOfBanana);
4
In this JavaScript tutorial, we learned about lastIndexOf() method of Array: the syntax and few working examples with output and detailed explanation for each example.