stromback
stromback

Reputation: 3

How to get the average value of array in JavaScript

I'm writing a code that lets you type in 10 random numbers into a prompt window. The numbers are stored in an array called tal. I have figured out how to get the highest and the lowest value but I can't get the average. can someone help me with a solution or to get me on the right way?

Here's my code:

let tal = [];
for (i = 0; i < 10; i++) {
  tal[i] = prompt('Add a number: ', '');
  tal.sort(function(a, b) {
    return a - b
  });
}
document.body.innerHTML += Math.max.apply(null, tal) + '<br>';
document.body.innerHTML += Math.min.apply(null, tal) + '<br>';

Upvotes: 0

Views: 4448

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22365

Just in one line of code....

const avg = arr => arr.reduceRight((a,v,i)=>(a+=v,i?a:a/arr.length),0);

console.log( avg([])                               ); //  0 -> not NaN
console.log( avg([10,20,30])                       ); // 20
console.log( avg([92,88,12,77,57,100,67,38,97,89]) ); // 71.7

Upvotes: 0

Ben Lorantfy
Ben Lorantfy

Reputation: 963

You could do something like this:

var average = getAverage(tal);

function getAverage(arr) {
  var sum = 0;
  for(var i = 0; i < arr.length; i++) {
    sum += Number(arr[i]);
  }

  return sum / arr.length;
}

Upvotes: 2

norbitrial
norbitrial

Reputation: 15166

I think if you use reduce() to sum up the numbers first then dividing that number with the length you are getting the average of the numbers at the end.

From the documentation of Array.prototype.reduce():

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const numbers = [3,4,5,2,4,6,78,53,2,1,2];
const sum = numbers.reduce((a,c) => a + c, 0);
const avg = sum / numbers.length;

console.log(avg);

I hope that helps!

Upvotes: 7

Related Questions