The indexOf()
method is used to return the index position of the first match of a value in an array in TypeScript, as well as in JavaScript. This method returns an integer value. However, if the element does not exist in the array, then the method returns -1
.
array.indexOf(element)
element
: This is the element whose index we want to get.
The index of the first matching element, which is an integer, in the array is returned. If no such element exists, then a -1
integer value is returned.
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]// get and print index of some elementsconsole.log(names.indexOf("Theodore"))console.log(names.indexOf("James"))console.log(numbers.indexOf(10000))console.log(numbers.indexOf(0.9))console.log(cars.indexOf("TOYOTA"))
Note: In line 12, the method returns-1
because "TOYOTA" is not present in the array "Toyota".