-2

I have an array of countries and populations. How can I withdraw the amount of population in all countries?

[
  { name: 'Poland', population: 42 000 000},
  { name: 'Belarus', population: 9 500 000},
  { name: 'Moldova', population: 3 500 000},
  { name: 'Switzerland', population: 8 400 000}
]

function calculateAverageCountryPopulation(countries) {

}

The sum of the array elements is not difficult. But I don't know how to do this task.

var arr = [3, 2, 5, 6];

function arraySum(array) {
  var sum = 0;
  for (var i = 0; i < array.length; i++) {
    sum += array[i];
  }
  console.log(sum);
}
arraySum(arr);
adiga
  • 34,372
  • 9
  • 61
  • 83

2 Answers2

0

function calculateAverageCountryPopulation(countries) {
  return countries.map(x => x.population).reduce((acc, y) => acc + y)
}
Michael Ossig
  • 205
  • 2
  • 9
0

Use a reduce and divide.

const data = [
  { name: 'Poland', population: 42000000},
  { name: 'Belarus', population: 9500000},
  { name: 'Moldova', population: 3500000},
  { name: 'Switzerland', population: 8400000}
]
const calculateAverageCountryPopulation = (countries) => countries.reduce((a,{ population: p}) => a+=p,0)/countries.length;

console.log(calculateAverageCountryPopulation(data)); 
Bibberty
  • 4,670
  • 2
  • 8
  • 23