So…I’m trying to generate 12 months starting by a given month, but using a for loop (0-11). After that, each number will be converted in the corresponding month name. But my issue is in that for loop.
What I’ve done so far is the following:
const startMonth = 1;
for (let i = 0; i < 12; i++) {
const month =
i + startMonth < 12 ? i + startMonth : startMonth - i - 2;
}
So, this will generate 12 months starting with February and ending with January. It also work for startMonth=0, that will generate 12 months starting with January and ending with December.
However, the second part (the else clause) of this approach is wrong. It does not work for the rest of values. Any ideas how to adjust the for loop to make it right ?
>Solution :
You could adjust the value with remainder operator % and 12 to get a value between zero and smaller than 12.
const startMonth = 1;
for (let i = 0; i < 12; i++) {
console.log((startMonth + i) % 12);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }