I recently came across this problem and can\'t find a good answer anywhere (hence the question).
I want to restart the loop once i reach the end yet only loop a finite a
You don't need to restart the loop, just use the modulus operator to wrap your array indexes around.
And you need to fix the order of dayNames
so it corresponds with what getDay()
returns. And the loop needs to run 7 times, not just 6 to get the entire week.
const dayNames = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
const rawDate = new Date();
const dayNum = rawDate.getDay();
const week = [];
for (let i = dayNum; i < dayNum + 7; i++) {
week.push(dayNames[i % 7]);
}
console.log(week);