我有一个这样的数组:
var a = [
{
"date": "2014-02-06T13:40:09.475Z",
"foo": "0"
},
...
{
"date": "2014-02-14T10:35:25.862Z",
"foo": "19"
}
];
我想按日期对项目进行排序。 date
字段是字符串化的ISODate
。这个数组按这种方式排序:
a.sort(function (f1, f2) {
return new Date(f1.date) > new Date(f2.date);
});
问题是数组未按预期排序。
暂停o
数组
var o = [];
for (var i = 0; i < a.length; ++i) {
o.push((new Date(a[i].date)).toString());
}
o
包含:
[
// 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)"
]
如你所见,还有其他奇怪的事情。如何解决这个问题?在服务器端,这些文档来自MongoDB数据库,但它们以相同的方式排序。
我创建了一个JSFIDDLE来演示此问题。问题出在哪?
答案 0 :(得分:1)
sort()
要求返回值为正数或负数(而不是0),除非它们是相等的(当你使用0时) - 如果你的布尔测试返回是的,它被视为等于(不是它更低),因为+false === 0
。你应该这样做:
a.sort(function (f1, f2) {
return new Date(f1.date) > new Date(f2.date) ? 1 : -1;
});
请参阅更新的JSFiddle here。