find the average of all elements in an array in typescript

You can find the average of all elements in an array in TypeScript by using the reduce() method to sum up all the elements in the array, and then dividing the sum by the length of the array.

Here's an example code snippet:

index.ts
const array: number[] = [1, 2, 3, 4, 5];
const sum = array.reduce((a, b) => a + b, 0);
const avg = sum / array.length;
console.log(avg); // Output: 3
150 chars
5 lines

In this code, we first define an array of numbers. We then use the reduce() method to sum up all the elements in the array. The reduce() method takes two arguments: a callback function and an initial value. The callback function takes two parameters, an accumulator and the current value of the array. In this example, we use an arrow function to add the accumulator and the current value together, starting with an initial value of 0.

Once we have the sum of all the elements in the array, we can calculate the average by dividing the sum by the length of the array. Finally, we log the average to the console.

gistlibby LogSnag