I'm working with an array of objects in Javascript and need to sort them by date and time. Here's the setup:
place
- title
- date (optional)
- time (optional)
Conceptually, the application allows users to create a list of places they're planning to go. The array of events is manually ordered at first, and users can optionally add date and time values to places. I'm providing an button to sort by date...places with null dates need to be placed at the bottom of the list.
Right now, it's behaving differently across browsers. Here's the code (assume I have a handle on the _places array and the _list object):
var _orderByDate = function (e) {
YUE.preventDefault(e); // yui
_places.sort(function (a, b) {
var dateA = new Date(a.date),
dateB = new Date(b.date);
if ((!dateA === null) && (dateB === null)) return 0; //they're both null and equal
else if ((dateA === null) && (dateB != null)) return -1; //move a downwards
else if ((dateA != null) && (dateB === null)) return 1; //move b downwards
else if ((dateA == dateB)) return (a.time > b.time) ? 1 : ((b.time > a.time) ? -1 : 0);
else return (dateA > dateB) ? 1 : ((dateB > dateA) ? -1 : 0);
});
_list.updatePlaces(_places);
}
If you recognize the sort code above, that's because I got the basics from another post, but I felt this one deserved it's own since it deals with dates...the other was just dealing with null values and text.
Anyway, in Chrome, the list seems to sort in a random order, and it keeps sorting differently every time I execute the _orderByDate function. In Safari, it sorts mostly correct the first time, but puts one null date place at the top of the list. In Firefox, nothing happens at all.
I'm a bit of a beginner, and I don't have a CS background at all, so I'm not adept at the basics like arrays, dates, times etc...and my debugging skills are limited to the Firebug console. No errors are being reported, so I really have no idea what's going wrong.
One thing to note, if I eliminate the date type from the function so it sorts the items as strings, it works correctly...but that means 1/10/2011 would sort before 1/9/2011, so I think I need the date type in there.
Any ideas what's going wrong? Is there a smarter way to do what I'm trying to do?
EDIT: Adding log values
First sort (Chrome):
- 08/01/2010
- null
- null
- 08/03/2010
- null
- null
- null
- null
- 7/01/2010
- null
- null
- null
Second sort (Chrome):
- 08/01/2010
- null
- null
- null
- 07/01/2010
- null
- null
- null
- null
- null
- 8/03/2010
- null
- null