const populations = [42000000, 9500000, 3500000, 8400000];
How can i fix this?
function calculateAverageCountryPopulation(populations) {
const initialValue = 0;
const sum =
populations.reduce((a, b) => a b, initialValue) / populations.length;
return sum;
}
console.log(calculateAverageCountryPopulation(populations));
CodePudding user response:
Try this !
const populations = [42000000, 9500000, 3500000, 8400000];
function calculateAverageCountryPopulation(populations) {
const initialValue = 0;
return populations.length>0 ? populations.reduce((a, b) => a b, initialValue) / populations.length:0
};
console.log(calculateAverageCountryPopulation(populations));
CodePudding user response:
You could simply check if the array contains any elements
function calculateAverageCountryPopulation(populations) {
if (!populations.length) {
return 0;
}
const sum = populations.reduce((total, population) => total population, 0);
const average = sum / populations.length;
return average;
}