this is the array-
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
now, I want to store 3 months’ names in an array- like p = ["march", "feb", "jan"] but this code is giving p = ["march", "march", "feb"] this fails during last 3-4 days of the month. are default days considered to be 28? Please suggest how to improve
var value = 3;
var d = new Date();
var p = [];
for (let i = 0; i < value; i++) {
var monthName = this.state.monthsarray[d.getMonth()];
p.push(monthName);
d.setMonth(d.getMonth() - 1);
}
2
Answers
I'm still trying to figure out why this duplicates month names but a workaround I'm currently using is-
You may consider adjusting your code to handle the edge case where the current month is
January
by taking the remainder of the previous month index and adding 12.Updated Code:
Edit: Suggestion based on the comment
You can even consider creating a new date object in each iteration and use that to get the previous month’s name.