JavaScript Array lastIndexOf()
Method
Example
Find the position of the array element "Apple":
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
a Output:
2
The above example output means "Apple" is located at the 2nd position in the array.
Definition and Usage
The lastIndexOf()
method returns the last occurrence of a specified element in the array, searching backwards from the end of the array.
If the element to search for is not found, the method returns -1.
The method searches for the specified element item
from the end of the array towards the beginning. The search starts at the specified start
position in the array or at the end of the array if the start
parameter is not specified. If an item
is found, it returns the position of the first occurrence of item
when searching backwards. Array indexing starts at 0.
If the specified element is not found in the array, it returns -1.
Tip: If you want to find the first occurrence of an element in the array, use the indexOf() method.
Browser Support
All major browsers support the lastIndexOf()
method, but it is not supported in Internet Explorer 8 and earlier versions.
Syntax
Parameter Values
Parameter | Description |
---|---|
item | Required. The string value to search for. |
start | Optional integer parameter. Specifies the position in the array to start the search from. Its valid range is from 0 to stringObject.length - 1. If omitted, the search starts from the last character of the array. |
Return Value
Type | Description |
---|---|
Number | Returns the position of the last occurrence of searchvalue before fromindex in stringObject . |
Technical Details
| JavaScript Version: | 1.6 | | --- | --- |
More Examples
Example
Find the position of "Apple" in the array:
a Output:
Example
Find the position of "Apple" starting from the 4th position in the array:
a Output: