Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of events by month in JavaScript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{ 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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading