Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
'use strict';

// write your code here
const populationSpans = document.querySelectorAll('.population');
const populationArray = Array.from(populationSpans);
const populationNumbers = populationArray.map((span) => {
const text = span.textContent;
const cleanText = text.replace(/[^\d]/g, '');
const number = Number(cleanText);

return number;
});

const total = populationNumbers.reduce((acc, num) => {
return acc + num;
}, 0);
const average = Math.round(total / populationNumbers.length);
const totalFormatted = total.toLocaleString();
const averageFormatted = average.toLocaleString();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requires the calculated numbers to have the 'same numeric style as populations presented'. The presented populations are whole numbers. When you calculate the average, it's likely to be a floating-point number (e.g., 12345.67). Using toLocaleString() directly on this will result in a formatted string with decimals (e.g., "12,345.67"), which doesn't match the style of the other population figures.

Consider rounding the average to the nearest whole number before formatting it. Math.round() would be a good function to use for this.

const totalSpan = document.querySelector('.total-population');
const averageSpan = document.querySelector('.average-population');

totalSpan.textContent = totalFormatted;
averageSpan.textContent = averageFormatted;
Loading