diff --git a/src/index.html b/src/index.html index 111e9cd2..d445fa71 100644 --- a/src/index.html +++ b/src/index.html @@ -24,6 +24,7 @@

TOP 10 LARGEST COUNTRIES BY POPULATION

/> China: + 1,439,234,240
  • diff --git a/src/scripts/main.js b/src/scripts/main.js index c6e3f878..ea943bd8 100644 --- a/src/scripts/main.js +++ b/src/scripts/main.js @@ -1,3 +1,25 @@ 'use strict'; // write your code here +function formatNumber(num) { + return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); +} + +function calculatePopulation() { + const populationElements = document.querySelectorAll('.population'); + + const populations = Array.from(populationElements).map((el) => { + return parseInt(el.textContent.replace(/,/g, ''), 10); + }); + + const total = populations.reduce((acc, curr) => acc + curr, 0); + const average = total / populations.length; + + const formattedTotal = formatNumber(total); + const formattedAverage = formatNumber(Math.round(average)); + + document.querySelector('.total-population').textContent = formattedTotal; + document.querySelector('.average-population').textContent = formattedAverage; +} + +calculatePopulation();