Group Forecast Entries by Local Date
Group Forecast Entries by Local Date
Task
Turn the forecast’s many three-hour entries into groups representing local calendar days.
Open
Add getLocalDateParts() and the first part of displayForecast().
Implementation
function getLocalDateParts(timestamp, timezone) {
const d = new Date((timestamp + timezone) * 1000);
return {
day: new Intl.DateTimeFormat("en-US", {
weekday: "short",
timeZone: "UTC"
}).format(d),
date: new Intl.DateTimeFormat("en-US", {
day: "numeric",
month: "short",
timeZone: "UTC"
}).format(d)
};
}
function displayForecast(data) {
state.lastForecast = data;
const byDay = new Map();
data.list.forEach(item => {
const parts = getLocalDateParts(item.dt, data.city.timezone);
const key = parts.date;
if (!byDay.has(key)) byDay.set(key, []);
byDay.get(key).push(item);
});
console.log([...byDay.entries()]);
}
A Map gives each local date an array of forecast entries. Using the destination timezone is important because a three-hour entry near midnight can belong to a different calendar date locally than it appears to in UTC.
Test
Search for a city and inspect the grouped dates. You should see arrays containing several forecast entries for each date. Remove the temporary log.
Expected result
The forecast data is organized into local days and is ready to render.
Checkpoint
Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.