To calculate the average of an array in TypeScript, you can use the reduce method to sum up all the elements in the array, then divide the result by the length of the array:
index.ts149 chars5 lines
Here's an example usage:
index.ts112 chars4 lines
In this example, we define a function called average
that takes an array of numbers as input and returns a single number as the output. The function uses the reduce
method to calculate the sum of all the elements in the array and then divides the sum by the length of the array to get the average. We then create an array of numbers and call the average
function to calculate the average value of the array. Finally, we print the output to the console.
gistlibby LogSnag