How to use the forEach method In Typescript
The forEach method iterates over each element of the array thus incrementing a counter for each element and counting the number of elements in the array
Syntax:
array.forEach(() => {count++;} );
Example: The below code will explain the use of the forEach method to find number of elements in an array.
const array: number[] = [1, 2, 3, 4, 5];
let count: number = 0;
array.forEach(() => {
count++;
});
console.log("Total number of elements: ",
count);
Output:
Total number of elements: 5
How to find the Total Number of Elements in an Array in TypeScript ?
In TypeScript, arrays are a common data structure used to store collections of elements. You can store multiple elements of different or the same data type inside them by explicitly typing.
The below methods can be used to accomplish this task:
Table of Content
- Using the length property
- Using the forEach method
- Using the reduce method
- Using a for Loop