I need to create a function in Javascript that is called calculateAverage which accepts arrays of numbers. The function should return the average in the array. If the array is empty, return 0.
I am new to coding and have only studied python.
int calculateAverage(int numbers_count, int* numbers) {
calculateAverage([50, 21, 80])
calculateAverage([30, 39, 58, 11])
calculateAverage([200])
calculateAverage([])
CodePudding user response:
this can be a solution:
function calculateAverage(arr) {
const sum = arr.reduce((acc, curr) => acc curr, 0)
return sum / arr.length
}
const arr = [5,10,1,5,20,50,30,25];
const average = calculateAverage(arr);
console.log(average)
CodePudding user response:
you can do that like this...
function calculateAverage(arr) {
const rslt = arr.reduce((a, b) => a b, 0) / arr.length;
return 0 === ~~rslt ? 0 : rslt;
}
console.log(calculateAverage([30, 39, 58, 11]));