-1

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"]

  • Hi, check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – malarres Nov 10 '21 at 10:10
  • I was able to create a solution to this by simply typing the function name and hitting tab while using Copilot. https://travis.media/how-to-use-github-copilot-vscode/ - I think Copilot can be great for new developers who want to learn good ways of solving problems. As long as you take the time to understand the code. – wuno Nov 10 '21 at 10:26
  • `const getPrev = month => { const m = monthsarray.indexOf(month); return monthsarray[(m+monthsarray.length-1)%monthsarray.length];}` – mplungjan Nov 10 '21 at 10:34
  • The marked duplicate doesn't answer this question. – RobG Nov 10 '21 at 12:23
  • @mplungjan—dunno why you bother with `const m`, it's only used once and forces a lot of extra typing: `const getPrev = month => monthsarray[(monthsarray.indexOf(month) + monthsarray.length - 1) % monthsarray.length];` :-) – RobG Nov 10 '21 at 12:29
  • @RobG for clarity/readability – mplungjan Nov 10 '21 at 12:37
  • @RobG [Now it does](https://stackoverflow.com/a/69911846/295783) – mplungjan Nov 10 '21 at 12:47

3 Answers3

0

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"));
Azad
  • 5,144
  • 4
  • 28
  • 56
-1
function prevMonth(month) {
    const index = monthsarray.indexOf(month);
    if (index > 0) {
        return monthsarray[index - 1];
    }
    if (index === 0) {
        return monthsarray[monthsarray.length - 1];
    }
    throw new Error('Invalid Month given');
}
Tom
  • 1,158
  • 6
  • 19
-1

let monthsarray1= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ;

let m="May";

console.log(pvsMonth(m))


function pvsMonth(m){

    let ln=monthsarray1.length

   

    let idx=monthsarray1.indexOf(m)

 
    
    if(idx==0){
    return  monthsarray1[ln-1]
    }else{
        return  monthsarray1[idx-1]
    
    }
}
Vivek Vs
  • 80
  • 4