average in typescript

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.ts
function average(arr: number[]): number {
  const sum: number = arr.reduce((acc: number, val: number) => acc + val, 0);
  return sum / arr.length;
}
149 chars
5 lines

Here's an example usage:

index.ts
const arr: number[] = [4, 8, 15, 16, 23, 42];
const avg: number = average(arr);
console.log(avg); // Output: 18
112 chars
4 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