TypeScript Array lastIndexOf()
Syntax & Examples
Array.lastIndexOf() method
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.
Syntax of Array.lastIndexOf()
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.
Parameters
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). |
Return Type
Array.lastIndexOf() returns value of type number
.
✐ Examples
1 Using lastIndexOf() to find the last occurrence of a number
The lastIndexOf() method can be used to find the index of the last occurrence of a number in an array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 1, 2, 3]. - Use
lastIndexOf(2)
to find the last occurrence of the number 2 in the array. - Store the result in
index
. - Log
index
to the console.
TypeScript Program
const arr = [1, 2, 3, 1, 2, 3];
const index = arr.lastIndexOf(2);
console.log(index);
Output
4
2 Using lastIndexOf() to find the last occurrence of a string
The lastIndexOf() method can be used to find the index of the last occurrence of a string in an array.
For example,
- Create an array
arr
with string values ['apple', 'banana', 'cherry', 'apple']. - Use
lastIndexOf('apple')
to find the last occurrence of the string 'apple' in the array. - Store the result in
index
. - Log
index
to the console.
TypeScript Program
const arr = ['apple', 'banana', 'cherry', 'apple'];
const index = arr.lastIndexOf('apple');
console.log(index);
Output
3
3 Using lastIndexOf() with a fromIndex parameter
The lastIndexOf() method can be used with a fromIndex parameter to start the search from a specific index.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 1, 2, 3]. - Use
lastIndexOf(2, 3)
to find the last occurrence of the number 2 in the array, starting the search from index 3. - Store the result in
index
. - Log
index
to the console.
TypeScript Program
const arr = [1, 2, 3, 1, 2, 3];
const index = arr.lastIndexOf(2, 3);
console.log(index);
Output
1
Summary
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.