I've been looking and haven't found a simple question and answer on stack overflow looking into finding the average of an array.
This is the array that I have
const grades = [80, 77, 88, 95, 68];
I first thought that the answer to this problem would be something like this:
let avg = (grades / grades.length) * grades.length console.log(avg)
However, this gave me an output of NaN.
So then I tried this:
for (let grade of grades) avg = (grade / grades.length) * grades.length console.log(avg)
This gave me an output of 68. (I'm not sure why).
So with this I have two questions. 1. Why was my output 68? and 2. Could somebody help me out with actually finding the average of an array?
You calculate an average by adding all the elements and then dividing by the number of elements. var total = 0; for(var i = 0; i < grades. length; i++) { total += grades[i]; } var avg = total / grades.
Simple approach to finding the average of an array We would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean.
Example 1 to calculate the average using arrays First, create an array with values and run. the for loop to find the sum of all the elements of the array. Finally, divide the sum with the length of the array to get the average of numbers.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
With ES6 you can turn Andy's solution into as a one-liner:
const average = (array) => array.reduce((a, b) => a + b) / array.length; console.log(average([1,2,3,4,5]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With