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)
)
}
>Solution :
You could sort by the indices of the months.
const
MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
events = [{ event: 'prom', month: 'MAY' }, { event: 'graduation', month: 'JUN' }, { event: 'dance', month: 'JAN' }];
events.sort((a, b) => MONTHS.indexOf(a.month) - MONTHS.indexOf(b.month));
console.log(events);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you have sometime no month property or a value different of the given months, you could add a default value for moving this item to top (0) or bottem (Number.MAX_VALUEor a larger value than the length of the array).
const
MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
events = [{ event: 'prom', month: 'MAY' }, { event: 'party', month: '' }, { event: 'graduation', month: 'JUN' }, { event: 'dance', month: 'JAN' }];
events.sort((a, b) =>
(MONTHS.indexOf(a.month) + 1 || Number.MAX_VALUE) -
(MONTHS.indexOf(b.month) + 1 || Number.MAX_VALUE)
);
console.log(events);
.as-console-wrapper { max-height: 100% !important; top: 0; }