How to write forEach method without repeating my code? ShowWeather function javascript

Viewed 31
function showForecastWeather(data) {
    forecastTitle.forEach((title) => {
        
        if (title.dataset.src === '1') {
            const d = new Date(data.list[7].dt * 1000);
            const dayName = days[d.getDay()];
            title.innerText = dayName.slice(0,3);
        };
        if (title.dataset.src === '2') {
            const d = new Date(data.list[15].dt * 1000);
            const dayName = days[d.getDay()];
            title.innerText = dayName.slice(0, 3)
        };
        if (title.dataset.src === '3') {
            const d = new Date(data.list[23].dt * 1000);
            const dayName = days[d.getDay()];
            title.innerText = dayName.slice(0, 3)
        };
        if (title.dataset.src === '4') {
            const d = new Date(data.list[31].dt * 1000);
            const dayName = days[d.getDay()];
            title.innerText = dayName.slice(0, 3)
        };
        if (title.dataset.src === '5') {
            const d = new Date(data.list[39].dt * 1000);
            const dayName = days[d.getDay()];
            title.innerText = dayName.slice(0, 3)
        };

    });

How can I write this without repeating my code so much? Like as a function or something? Is it possible to use index parameter in forEach() method to display API data?

1 Answers

The only thing that changes between the conditions is the index you use to access the list array. As such you can genericise your logic by calculating this value from the src. Something like this:

function showForecastWeather(data) {
  forecastTitle.forEach(title => {
    const index = (parseInt(this.dataset.src, 10) * 8) - 1;
    const d = new Date(data.list[index].dt * 1000);
    const dayName = days[d.getDay()];
    title.innerText = dayName.slice(0, 3);
  });
}
Related