raxinaga
raxinaga

Reputation: 421

How to calculate the previous months in JS?

In JavaScript,

How to calculate all the previous months from this month (for a year) in the fastest way?

Say, for input: Jun should expect Jun,May,Apr,...Jan,Dec...Jun

Upvotes: 0

Views: 63

Answers (2)

Manuel Reis
Manuel Reis

Reputation: 574

You could follow an approach like this:

const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

function getPreviousMonths(currentMonth) {
    let index = MONTHS.indexOf(currentMonth);
    let result = [];

    for(let j = 0; j < MONTHS.length; j++) {
        let access = index - j;
        if(access < 0) {
            access += MONTHS.length;
        }
        result.push(MONTHS[access]);
    }

    return result.join(",");
}

Upvotes: 1

bahek2462774
bahek2462774

Reputation: 664

I would rather have some mapping, like this. let months = [Jaunary, February, March, April, May]

Then Having got for example 'March' - find its index in array months, and take previous index or whatever you want

Upvotes: 0

Related Questions