I have an array like this:
var a = [
{
"date": "2014-02-06T13:40:09.475Z",
"foo": "0"
},
...
{
"date": "2014-02-14T10:35:25.862Z",
"foo": "19"
}
];
I want to sort the items by date. The date
field is a stringified ISODate
. This array is sorting this way:
a.sort(function (f1, f2) {
return new Date(f1.date) > new Date(f2.date);
});
The issue is that the array is not sorted as supposed.
Pusing the dates in o
array
var o = [];
for (var i = 0; i < a.length; ++i) {
o.push((new Date(a[i].date)).toString());
}
o
contains:
[
// Isn't this supposed to be near the other days?
"Tue Feb 04 2014 16:37:39 GMT+0200 (EET)", // |
"Thu Feb 06 2014 15:40:09 GMT+0200 (EET)", // |
"Thu Feb 06 2014 10:39:08 GMT+0200 (EET)", // |
"Wed Feb 05 2014 16:07:50 GMT+0200 (EET)", // |
"Tue Feb 04 2014 16:38:56 GMT+0200 (EET)", // <-/
"Tue Feb 04 2014 16:54:11 GMT+0200 (EET)",
"Tue Feb 04 2014 16:52:45 GMT+0200 (EET)",
"Tue Feb 11 2014 14:34:29 GMT+0200 (EET)",
"Thu Feb 06 2014 17:14:11 GMT+0200 (EET)",
"Tue Feb 11 2014 14:34:35 GMT+0200 (EET)",
"Fri Feb 07 2014 11:44:46 GMT+0200 (EET)",
"Thu Feb 06 2014 17:33:33 GMT+0200 (EET)",
"Fri Feb 07 2014 15:20:15 GMT+0200 (EET)",
"Tue Feb 11 2014 11:59:24 GMT+0200 (EET)",
"Tue Feb 11 2014 12:38:11 GMT+0200 (EET)",
"Tue Feb 11 2014 14:54:07 GMT+0200 (EET)",
"Tue Feb 11 2014 14:54:24 GMT+0200 (EET)",
"Wed Feb 12 2014 17:21:28 GMT+0200 (EET)",
"Thu Feb 13 2014 15:42:15 GMT+0200 (EET)",
"Fri Feb 14 2014 12:35:25 GMT+0200 (EET)"
]
And there are other weird things, as you see. How can this issue be solved? On the server side these documents come from a MongoDB database, but they are sorted in the same way.
I created a JSFIDDLE that demonstrates this issue. Which is the problem?