JavaScript Array lastIndexOf()
Examples
Find the last index of "Apple":
let index = fruits.lastIndexOf("Apple");
More than one apple:
let index = fruits.lastIndexOf("Apple");
More examples below.
Description
The lastIndexOf()
method returns the last index (position) of a specified value.
The lastIndexOf()
method returns -1 if the value is not found.
The lastIndexOf()
starts at a specified index and searches from right to left
(from the given postion to the beginning of the array).
By defalt the search starts at the last element and ends at the first.
Negative start values counts from the last element (but still searches from right to left).
Array Find Methods:
Method | Finds |
---|---|
includes() | Returns true if an array contains a specified value |
indexOf() | The index of the first element with a specified value |
lastIndexOf() | The index of the last element with a specified value |
find() | The value of the first element that passes a test |
findIndex() | The index of the first element that passes a test |
findLast() | The value of the last element that passes a test |
findLastIndex() | The index of the last element that passes a test |
Syntax
Parameters
The value to search for.
Where to start the search.
Default is the last element (array.length-1).
Negative start values counts from the last element (but still searches from right to left).
Return Value
-1 if the item is not found.
More Examples
Start the search at position 4:
let index = fruits.lastIndexOf("Apple", 4);
Start the search at the second last position:
let index = fruits.lastIndexOf("Apple", -2);
Array Tutorials:
Browser Support
lastIndexOf()
is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |