Array.prototype.lastIndexOf
Finds a value from the end of an array and returns its index.
Available since: ES5
Syntax
array.lastIndexOf(searchElement, fromIndex)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchElement | any | The value to find. |
| fromIndex | number | Optional. The position to search backwards from. From the end by default. |
Return value
numberThe index of the last match, or -1.
Examples
The last occurrence:
const marks = [5, 3, 5, 4];
console.log(marks.lastIndexOf(5));
console.log(marks.indexOf(5));Output:
2
0Notes
Like indexOf(), it compares strictly and returns -1 when nothing is found.
See also
- Array.prototype.indexOf — Finds a value in an array and returns its index.
- Array.prototype.findLastIndex — Returns the index of the last element that passes a test.
In the tutorial
- Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.