TypeScript Array indexOf() Method
The Array.indexOf() method in TypeScript is used to find the index of the first occurrence of a specified element in an array. If the element is not found, it returns -1.
Syntax
array.indexOf(searchElement[, fromIndex])
Parameter: This method accepts two parameters as mentioned above and described below:
- searchElement: This parameter is the Element to locate in the array.
- fromIndex: This parameter is the index at which to begin the search.
Return Value: This method returns the index of the found element.
The below examples illustrate the Array indexOf() method in TypeScript.
Example 1: Finding an Element in an Array
In this example, the indexOf() method is used to find the index of the first occurrence of the element 5 in the array.
let numbers: number[] = [1, 2, 3, 5, 5, 6];
let index = numbers.indexOf(5);
console.log(index); // Output: 3
Output:
3
Example 2: Searching from a Specific Index
In this example, the indexOf() method is used to find the index of the element 5 in the array, starting the search from index 4.
let numbers: number[] = [1, 2, 3, 5, 5, 6];
let index = numbers.indexOf(5, 4);
console.log(index); // Output: 4
Output:
4
Example 3: Element Not Found
In this example, the indexOf() method is used to search for an element 10 that is not present in the array.
let numbers: number[] = [1, 2, 3, 5, 6];
let index = numbers.indexOf(10);
console.log(index); // Output: -1
Output:
-1