Skip to content
Advertisement

Generate an array of years with duplicates of each year + labeled season

How do i dynamically generate an array of years starting from 2004 till the current year, with each year labeled with “Spring” and “Fall” like in the attached picture?

enter image description here

Thank you!

Advertisement

Answer

You can easily achieve this result using flatMap. If you don’t care about the current year’s season then you can get all results up to the current year.

function generateArrayWithSeason(start) {
  return Array(new Date().getFullYear() + 1 - start)
    .fill("")
    .flatMap((_, i) => [`${start + i} SPRING`, `${start + i} FALL`]);
}

console.log(generateArrayWithSeason(2004));
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you want results according to current year’s spring and fall

spring runs from March 1 to May 31

fall (autumn) runs from September 1 to November 30

function generateArrayWithSeason(start) {
  const month = new Date().getMonth();
  let currentYear = new Date().getFullYear();
  const springMonths = [3, 4, 5];
  const fallMonths = [9, 10, 11];

  return Array(currentYear + 1 - start)
    .fill("")
    .flatMap((_, i) => {
      if (currentYear === start + i) {
        if (springMonths.includes(month)) return [`${start + i} SPRING`];
        if (fallMonths.includes(month)) return [`${start + i} FALL`];
      }
      return [`${start + i} SPRING`, `${start + i} FALL`];
    });
}

console.log(generateArrayWithSeason(2004));
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement