Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
Function 'calculateAverageCountryPopulation' should work for an empty array

enter image description here

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!