Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate month by month starting with a given index?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading