-1

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?

4

1 回答 1

1

sort()要求返回值是正数或负数(而不是 0),除非它们是相等的(那是您使用 0 的时候)——如果您的布尔测试返回 false,则将其视为是相等的(不是说它更低),因为+false === 0. 你应该这样做:

a.sort(function (f1, f2) {
    return new Date(f1.date) > new Date(f2.date) ? 1 : -1;
});

在此处查看更新的 JSFiddle 。

于 2014-02-16T14:40:44.323 回答