The lastIndexOf() method in JavaScript is used to find the last occurrence of a specified element in an array. It searches the array from right to left, starting at the specified index or at the end if no start index is provided. It returns the index of the last occurrence of the element, or -1 if the element is not found.
Syntax
array.lastIndexOf(searchElement, fromIndex);
Parameters
Parameters | Descriptions |
---|---|
searchElement | The element to search for in the array. |
fromIndex (Optional) | The index at which to start searching for the element. If omitted, the search starts from the last element of the array. |
Return Value
Return Type | Description |
---|---|
Number | The index of the last occurrence of the element, or -1 if not found. |
Example 1: Using lastIndexOf() to Find the Last Occurrence
This code demonstrates how to use the lastIndexOf() method to find the index of the last occurrence of a specific element in an array.
let Arr = [ 1, 2, 3, 4, 5, 2, 3]; console.log(Arr.lastIndexOf(3)); console.log(Arr.lastIndexOf(6));
Output:
6
-1
Example 2: Using lastIndexOf() Method
You can specify the fromIndex
parameter to start the search from a specific index.
let Arr = [1, 2, 3, 4, 5, 2, 3]; console.log(Arr.lastIndexOf(3, 4)); console.log(Arr.lastIndexOf(3, 1));
Output:
2
-1
Example 3: Using lastIndexOf() with NaN
The lastIndexOf()
method can also be used to check for the last occurrence of NaN
in an array.
let Arr = [1, 2, NaN, 4, 5, NaN]; console.log(Arr.lastIndexOf(NaN));
Output:
-1
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |