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>';
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>';
Share
Improve this question
edited Feb 4, 2020 at 20:37
norbitrial
15.2k10 gold badges39 silver badges64 bronze badges
asked Feb 4, 2020 at 20:30
strombackstromback
31 silver badge5 bronze badges
3
- 2 why do you sort the array? – Nina Scholz Commented Feb 4, 2020 at 20:36
- Does this answer your question? 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 Commented Feb 4, 2020 at 20:38
-
You can calculate the average like this:
var average = eval(numbers.map(Number).join('+'))/numbers.length
wherenumbers
is the variable which contains your numbers – Iter Ator Commented Feb 4, 2020 at 20:39
3 Answers
Reset to default 7I 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!
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;
}
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