To count the number of occurrences of a specified element in an array in TypeScript, you can use methods like filter
or loops to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.filter
method to filter the elements that match element 30.const numbers: number[] = [10, 20, 30, 40, 30, 50];
const count: number = numbers.filter(num => num === 30).length;
console.log(`Number of occurrences of element 30: ${count}`);
Number of occurrences of element 30: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry', 'banana'.const fruits: string[] = ['apple', 'banana', 'cherry', 'banana'];
let count: number = 0;
for (const fruit of fruits) {
if (fruit === 'banana') {
count++;
}
}
console.log(`Number of occurrences of element 'banana': ${count}`);
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in TypeScript language with well detailed examples.