Array.prototype.lastIndexOf()
Overview.
The Array.prototype.lastIndexOf()
method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, from the end to the beginning.
Syntax
array.lastIndexOf(searchElement[, fromIndex])
Parameters
searchElement
(required): The element to search for in the array.fromIndex
(optional): The index at which to start searching backwards. By default, the search starts at the last index in the array.
return value
The index of the last occurrence of the specified element in the array, or -1
if it is not found.
Examples
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const lastIndex = arr.lastIndexOf(4);
console.log(lastIndex); // Output: 5
Use Cases
Searching for the last occurrence of a value in an array
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const lastIndex = arr.lastIndexOf(4);
console.log(lastIndex); // Output: 5
Checking if an element exists in an array
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const hasElement = arr.lastIndexOf(6) !== -1;
console.log(hasElement); // Output: false
Finding the last index of a specific value in an array
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const lastIndex = arr.lastIndexOf(3);
if (lastIndex !== -1) {
arr.splice(lastIndex, 1);
}
console.log(arr); // Output: [1, 2, 3, 4, 5, 4, 2, 1]
Notes
The lastIndexOf()
method returns the index of the last occurrence of the specified element in the array, and does not modify the array.
This page was updated on -
Found an error or have feedback on our docs?
Create an issue on GitHub and let us know! Your input helps improve our documentation for everyone in the community.
Report error, send feedback on Github