How could I sort an array of events by the month they are occuring in?
For instance, I want to sort this events
array:
[{ event: 'prom', month: 'MAY' },
{ event: 'graduation', month: 'JUN' },
{ event: 'dance', month: 'JAN' }]
to become this array:
[{ event: 'dance', month: 'JAN' },
{ event: 'prom', month: 'MAY' },
{ event: 'graduation', month: 'JUN' }]
An array of MONTHS is also provided:
const MONTHS = [
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
];
I'm trying to sort the events
array using the sort method, but it is only sorting in alphabetical order. Could anyone help give me guidance to figure out how I can sort by the calendar order of months?
const MONTHS = [
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
];
function sortByMonth(events) {
events.sort((a,b) =>
a.month.localeCompare(b.month)
)
}