How to use the reduce method In Typescript
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.
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
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
Contact Us