Open In App

How to find the Total Number of Elements in an Array in TypeScript ?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using the length property

The 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.

JavaScript
const array: number[] = 
    [1, 2, 3, 4, 5];
const lengthUsingLengthProperty: number = 
    array.length;
console.log("Total number of elements: ", 
    lengthUsingLengthProperty);

Output:

Total number of elements: 5

Using the forEach method

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.

JavaScript
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

Using the reduce method

The reduce method accumulates the count of elements in the array by reducing the element in the array until array becomes empty.

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.

JavaScript
const array: number[] = 
    [1, 2, 3, 4, 5];
const count: number = 
    array.reduce(
        (acc) => acc + 1, 0);
console.log("Total number of elements:", 
    count);

Output:

Total number of elements: 5

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads