0

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>';
norbitrial
  • 14,716
  • 7
  • 32
  • 59
stromback
  • 3
  • 1
  • 5
  • 2
    why do you sort the array? – Nina Scholz Feb 04 '20 at 20:36
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) Use this and then just divide by array.length (basic average calc in math) – Calvin Nunes Feb 04 '20 at 20:38
  • You can calculate the average like this: `var average = eval(numbers.map(Number).join('+'))/numbers.length` where `numbers` is the variable which contains your numbers – Iter Ator Feb 04 '20 at 20:39

2 Answers2

6

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!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • this is the simplest solution and correct as long as you have reduce available (meaning you are not writing for IE). Otherwise the first answer using a for loop would have to be used. – Sandra Willford Feb 04 '20 at 21:04
2

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;
}
Ben Lorantfy
  • 963
  • 1
  • 7
  • 19