I’m trying to build a javascript array of objects, parsing dates using date.js, and then sort that aray of objects using date.js compare methods. Here is some code I put together to demonstrate my two problems.
Problem 1: How do I ignore and warn on dates that date.js can’t parse?
Problem 2: How can I sort an array of objects by those dates? (with or without date.js)
My intuition tells me that I’m doing this all wrong and there’s a better way. Ideas?
<script type="text/javascript" src="depend/date.js"></script>
<script type="text/javascript">
var timedata = ["tomorrow", "today", "next thursday", "2012-08-02T04:00:00.000Z"]; // test data
var myArrayOfObjects = [];
//Iterate through the timedata array
for(var row = 0; row < timedata.length; row++){
var cleanrow = true;
// Here is the first problem, on the 2012-08-02T04:00:00.000Z string can't be parsed (Date.parse(timestr) returns 0)
// even though it was previously created with .toISOString method below as a test
// Error: Ignoring row 3, could not parse this date: 2012-08-02T04:00:00.000Z
if (Date.parse(timedata[row])){
time = Date.parse(timedata[row]);
isoTime = time.toISOString();
}else{
console.log("Ignoring row " + row + ", could not parse this date: " + timedata[row]);
cleanrow = false;
}
var xdata = "dummytestdata";
var weight = "dummytestdata";
if(cleanrow) {
myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight});
}
}
// Here is the second problem.
// Error: TypeError: Date.parse(a.xytime) is null
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return Date.parse(a.xytime).compareTo(Date.parse(b.xytime)); });
// Show that the objects are sorted by dates
for(var row = 0; row < myArrayOfObjects.length; row++) {
console.log(myArrayOfObjects[row].xytime);
}
</script>
Couple of little things
Consider declaring time and isoTime up in your var section, otherwise they just magically appear and the scoping is not defined.
Consider parsing
timedata[row]only once, and reusing the variable. It might clean up the code a bit.Is there any reason why you need the isoTime as a string, rather than just storing the date on the object you’re putting in the array? Strikes me that you could just store the date as well, and use that in the sort
Also, looking at the mozilla doco, the sort method acts on the array in place, rather than returning a new array.