Sorting dates without year in JavaScript

Sorting dates without year in JavaScript header image

When discussing the workings of the Mavention Anniversaries update with a client we found out that the sorting just didn’t cut it. By default our query would retrieve the anniversaries for this and the upcoming month  (with a certain limit of course), and then sort by anniversary. By default the search allows for sorting fairly easy by passing sortlist parameter into the query.

However using the sortlist is not always enough, in case of anniversaries sorting by them will result in having either the newest or the oldest anniversary first as it takes the year into account. So while you would expect the anniversaries to be sorted by their day in the month, using the default search sort will just not cut it. When discussing this problem we came up with a solution. Depending on how much anniversaries there are we could retrieve ‘all’ of them for the current (and next) month, and then use JavaScript to sort those dates.

We decided to write a custom sort function to sort the anniversaries correctly, so a little bit of background information on JavaScript and Sort operations might be useful. As we already used moment.js I used that in a small helper method that helps you sorting dates without the year. The helper method accepts a an array of objects with a property called anniversary. This anniversary date gets transformed using moment.js, and the input will be compared based on month and day (date). If the month of the values in the array is the same (0 will be outputted), it will fall back to the day, making sure that it is sorted both on month and day, providing a corrected sorted array.

sortByDateNoYear = function (adate, bdate) {
    var results,
        lhdate = moment(adate.anniversary),
        rhdate = moment(bdate.anniversary);

     results = lhdate.months() > rhdate.months() ? 1 : lhdate.months() < rhdate.months() ? -1 : 0;

     if (results === 0) results = lhdate.date() > rhdate.date() ? 1 : lhdate.date() < rhdate.date() ? -1 : 0;

     return results;
}

Keep in mind that the anniversary can be any property in your array, as long as it contains a value that can be parsed to a date by moment.js. Calling the helper can then be done with the following statement:

array.sort(sortByDateNoYear);

Obviously this might not be an option if you are required to sort thousands of items, but when testing it it all performed good with around 200 items. So it is a great solution for sorting the anniversaries using just JavaScript. Of course it is included in the latest release of the Mavention Anniversaries, as posted in Updates Mavention Birthdays and Mavention Anniversaries. You can find the latest version of the Mavention Anniversaries in the Office Store.

Loading comments…