-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);

0

2 Answers 2

0

function calculateAverageCountryPopulation(countries) {
  return countries.map(x => x.population).reduce((acc, y) => acc + y)
}

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks its working - can you give me a link to read more about this solution? Thank you!
This is not the average.
@Bibberty correct, the question asked for the sum
Yes, but the the function name .... :)
|
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)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.