.lastIndexOf()
Published Oct 15, 2021Updated Jul 13, 2023
Contribute to Docs
The .lastIndexOf()
array method returns the last index at which an element can be found. Otherwise, it returns -1
if the element is not found.
Syntax
array.lastIndexOf(searchElement, fromIndex);
searchElement
: The target element in the search.fromIndex
(optional): The starting index position that search begins. The default value offromIndex
isarray.length - 1
. Therefore, if undefined, the search starts from the last index.
Note: A negative
fromIndex
will offset from the end of the array to begin the search. The array is still searched backwards.
Examples
Searching for an element not in the given array:
const fruits = ['apple', 'orange', 'peach'];const lastIndexOfCherry = fruits.lastIndexOf('cherry');console.log(lastIndexOfCherry);// Output: -1
Searching for the element indigo
in an array of colors:
const rainbow = ['red','orange','yellow','green','blue','indigo','violet',];const checkIndigo = rainbow.lastIndexOf('indigo');console.log(checkIndigo);// Output: 5
Codebyte Example
The example below defines a new array cities
. The array lists the city 'Berlin'
twice (multiple matches will only return the last index within the index range where a match occurs):
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.