How could I calculate average using a function:
function calculate(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum = sum + array[i];
}
return sum;
}
document.write(calculate([24, 88, 12, 4]));
(I don't understand how to get the arguments length)
How could I calculate average using a function:
function calculate(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum = sum + array[i];
}
return sum;
}
document.write(calculate([24, 88, 12, 4]));
(I don't understand how to get the arguments length)
Share Improve this question edited Dec 17, 2016 at 16:06 jophab 5,50914 gold badges44 silver badges61 bronze badges asked Dec 17, 2016 at 14:14 U.P.U.P. 811 gold badge1 silver badge6 bronze badges 2 |7 Answers
Reset to default 11To get the average, just sum the values and divide by number of indices in the array, i.e. the length
function calculate(array) {
return array.reduce((a, b) => a + b) / array.length;
}
console.log(calculate([24, 88, 12, 4]));
You can calculate the average easily with reduce()
method:
const avg = array.reduce((a, b) => a + b) / array.length
Use the array's length property:
function calculate(array) {
var i = 0, sum = 0, len = array.length;
while (i < len) {
sum = sum + array[i++];
}
return sum / len;
}
Your function sum all the number in the array. in the return line you should change to something like this:
return sum / array.length;
And you should change this line:
console.log(calculate([24, 88, 12, 4]));
to this:
console.log(calculate({24, 88, 12, 4}));
You can try this way as well by using for-of loop.
function average(...nums) {
let total = 0;
for(const num of nums) {
total += num/nums.length;
}
return total;
}
console.log(average(24, 88, 12, 4));
This for...of loop should work perfectly
function average(...nums) {
let sum = 0;
let avg = 0;
for(const num of nums) {
sum += num;
avg = sum/nums.length;
}
return avg;
}
console.log(average(24, 88, 12, 4));
x = []
function average(...x) {
let sum = 0,
avg = 0;
for (let i of x ){
sum = sum + i;
avg = sum/x.length;
}
return avg
}
console.log(average(2, 6 , 8 , 14));
return sum / array.length;
? – Sebastian Simon Commented Dec 17, 2016 at 14:15