To get the index of a specified element in an array in TypeScript, you can use methods like indexOf
.
In this example,
numbers
with values 10, 20, 30, 40, 50.indexOf
method to find the index of a specific element in the array.indexOf
method returns the index of the first occurrence of the element, or -1 if the element is not found.const numbers: number[] = [10, 20, 30, 40, 50];
const index: number = numbers.indexOf(30);
console.log(`Index of element 30 is: ${index}`);
Index of element 30 is: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry'.indexOf
method to find the index of a specific element in the array.indexOf
method returns the index of the first occurrence of the element, or -1 if the element is not found.const fruits: string[] = ['apple', 'banana', 'cherry'];
const index: number = fruits.indexOf('banana');
console.log(`Index of 'banana' is: ${index}`);
Index of 'banana' is: 1
In this tutorial, we learned How to get the Index of Specified Element in an Array in TypeScript language with well detailed examples.