![]() |
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 propertyThe length property is used to get the length or size of an array. It can be used to get the total number of elements stored in the array. Syntax:array.length Example: The below code implements length property to find total number of elements in an array.
Output: Total number of elements: 5 Using the forEach methodThe 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.
Output: Total number of elements: 5 Using the reduce method
Syntax:const count = array.reduce((acc) => acc + 1, 0); Example: The below code will explain the use of the reduce method to find total number of elements in an array.
Output: Total number of elements: 5 Using a for LoopIn this approach we Iterating through the array using a for loop, incrementing a counter for each element until the end of the array is reached, then returning the total count. Example: In this example The function iterates through the array using a `for` loop, incrementing a count for each element, then returns the count. Finally, it logs the total count.
Output: Total number of elements: 5 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |