0

I want to show average of population of all the countries. I am trying to create one array from mapped data and then get average. I don't know how to create one array from the data. Or is there other way of doing it?

code:

function getAverage(countries) {
  countries.map((country) => {
    const countryPopulation = country.population;
    console.log(countryPopulation);
    return countryPopulation;
  });
}

This it what I get from console.log(countries.population) : Console.log result

1
  • 2
    .map returns the array you’re looking for. Log that result, not the individual countryPopulation values. Just look at the examples in the documentation. Commented Jul 7, 2021 at 13:21

2 Answers 2

1

use reduce to sum up all the populations, and divide by the number of countries to get an average. Theres no need to make a separate array to do this.

function getAverage(countries) {
  const sum = countries.reduce((acc, country) => acc + country.population,0);
  return sum/countries.length;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to create an array just to get average, there is a better way of doing it, here is my goto one liner to calculate average of arguments

const average = (...args) => args.reduce((a, b) => a + b) / args.length

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.