The lastIndexOf() method returns the index of the last occurrence of a specified value in an array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
The syntax of Array.lastIndexOf() method is:
lastIndexOf(searchElement: T, fromIndex?: number): number
This lastIndexOf() method of Array returns the index of the last occurrence of a specified value in an array.
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
fromIndex | optional | The index at which to start searching backwards. Defaults to the array's length minus one (arr.length - 1). |
Array.lastIndexOf() returns value of type number
.
The lastIndexOf() method can be used to find the index of the last occurrence of a number in an array.
For example,
arr
with numeric values [1, 2, 3, 1, 2, 3].lastIndexOf(2)
to find the last occurrence of the number 2 in the array.index
.index
to the console.const arr = [1, 2, 3, 1, 2, 3];
const index = arr.lastIndexOf(2);
console.log(index);
4
The lastIndexOf() method can be used to find the index of the last occurrence of a string in an array.
For example,
arr
with string values ['apple', 'banana', 'cherry', 'apple'].lastIndexOf('apple')
to find the last occurrence of the string 'apple' in the array.index
.index
to the console.const arr = ['apple', 'banana', 'cherry', 'apple'];
const index = arr.lastIndexOf('apple');
console.log(index);
3
The lastIndexOf() method can be used with a fromIndex parameter to start the search from a specific index.
For example,
arr
with numeric values [1, 2, 3, 1, 2, 3].lastIndexOf(2, 3)
to find the last occurrence of the number 2 in the array, starting the search from index 3.index
.index
to the console.const arr = [1, 2, 3, 1, 2, 3];
const index = arr.lastIndexOf(2, 3);
console.log(index);
1
In this TypeScript tutorial, we learned about lastIndexOf() method of Array: the syntax and few working examples with output and detailed explanation for each example.