From 7b058dc15cc10b8bb469cd63281068694f0b0b4f Mon Sep 17 00:00:00 2001 From: meryam wazeen Date: Tue, 26 Sep 2023 19:18:48 +0300 Subject: [PATCH] add task solution --- src/scripts/main.js | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/scripts/main.js b/src/scripts/main.js index c6e3f878..4be9f1c3 100644 --- a/src/scripts/main.js +++ b/src/scripts/main.js @@ -1,3 +1,29 @@ 'use strict'; -// write your code here +const populationElements = document.querySelectorAll('.population'); + +let totalPopulation = 0; + +populationElements.forEach((element) => { + const populationText = element.textContent.trim(); + const populationNumber = parseFloat(populationText.replace(/,/g, '')); + + if (!isNaN(populationNumber)) { + totalPopulation += populationNumber; + } +}); + +const averagePopulation = totalPopulation / populationElements.length; + +const formattedTotalPopulation = numberWithCommas(totalPopulation); +const formattedAveragePopulation = numberWithCommas(averagePopulation); + +document.querySelector('.total-population') + .textContent = formattedTotalPopulation; + +document.querySelector('.average-population') + .textContent = formattedAveragePopulation; + +function numberWithCommas(number) { + return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); +}