Skip to content

Instantly share code, notes, and snippets.

@MatiasDuhalde
Last active December 4, 2021 03:16
Show Gist options
  • Save MatiasDuhalde/e3ab4a47527f30feb264a3107f9e8112 to your computer and use it in GitHub Desktop.
Save MatiasDuhalde/e3ab4a47527f30feb264a3107f9e8112 to your computer and use it in GitHub Desktop.
Get array of N previous months before a month
const monthsLabels = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
const getPreviousMonths = (current, previous) => {
const startMonth = (current - (previous % 12) + 13) % 12;
const months = [];
for (let i = 0; i < previous; i++) {
months.push(monthsLabels[(startMonth + i) % 12]);
}
return months;
};
// Example call
// Get array of 20 months before April
getPreviousMonths(3, 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment