Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the average of an array using JS [duplicate]

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?

like image 403
kdweber89 Avatar asked Apr 09 '15 16:04

kdweber89


People also ask

How do you find the average of an array in JavaScript?

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.

How do you find the average of an array?

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.

How do you find the average of an array using a for each loop?

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.

How do you duplicate an array in JavaScript?

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.


1 Answers

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]));
like image 115
Austin Avatar answered Sep 28 '22 16:09

Austin