To check if a specified element is present 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 check if element 30 is present 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 check if element 'banana' is present 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 check if Specified Element is present in the Array in TypeScript language with well detailed examples.