Demonstrating a Function to Get the Last N Months in JavaScript
The Function: getLastSixMonths
getLastSixMonthsfunction getLastSixMonths(date) {
const yearOrMonthData = [];
for (let i = 13; i >= 0; i--) {
// Create a new Date object for the first day of the month (i months ago)
const lastSixMonth = new Date(date.getFullYear(), date.getMonth() - i, 1);
// Get the full month name for the current month
const monthName = lastSixMonth.toLocaleString("default", { month: "long" });
// Store the month name, year, and formatted string (month::year) in the array
yearOrMonthData.unshift({
name: `${monthName} ${lastSixMonth.getFullYear()}`,
monthOrYear: `${lastSixMonth.getMonth() + 1}::${lastSixMonth.getFullYear()}`
});
}
return yearOrMonthData;
}
// Example usage:
const date = new Date(); // Current date
const monthsData = getLastSixMonths(date);
console.log(monthsData);Practical Use Cases
Conclusion
PreviousWhen JavaScript's Set Falls Short for Ensuring Uniqueness in Arrays of ObjectsNextHow to Convert Numbers to Words in the Indian Numbering System Using JavaScript
Last updated