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.ts150 chars5 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