javascriptarraysfunctiondatetimemonthcalendar

How to get previous month name on given some month (in words not numerical value)?


I want a function that gives the full name of prev month for any given month[not just current month] Ex: prevMonth(August) = July; prevMonth(January)= December.

I'm new to js and can't figure out how to use this array to get the result:

monthsarray: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]


Solution

  • Are expecting a simple solution like this?

    var monthsarray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    
    function prevMonth(curMonth) {
    
      var curMonthIndex = monthsarray.indexOf(curMonth);
      var prevMonthIndex;
      if (curMonthIndex == 0) prevMonthIndex = monthsarray.length - 1;
      else if (curMonthIndex == monthsarray.length - 1) prevMonthIndex = 0;
      else prevMonthIndex = curMonthIndex - 1;
    
      return monthsarray[prevMonthIndex];
    }
    
    
    console.log(prevMonth("August"));
    console.log(prevMonth("December"));