【发布时间】:2016-10-08 17:48:58
【问题描述】:
我有一个这样的对象数组:
var example = [{
"description": "aaa",
"time": "12:15pm"
}, {
"description": "bbb",
"time": "10:10am"
}, {
"description": "ccc",
"time": "4:00pm"
}, {
"description": "ddd",
"time": "6:15pm"
}, {
"description": "eee",
"time": "1:10am"
}, {
"description": "fff",
"time": "5:00pm"
} ];
我想按time 值排序。
我已尝试应用 this solution,它用于字符串值数组:
example.sort(function (a, b) {
return new Date('1970/01/01 ' + a.time) - new Date('1970/01/01 ' + b.time);
});
console.log(example);
我也一直在参考 Mozilla Array.prototype.sort() 文档并尝试了以下似乎不起作用的方法:
example.sort(function(a, b) {
if (new Date(a.time) > new Date(b.time)) {
return 1;
}
if (new Date(a.time) < new Date(b.time)) {
return -1;
}
// a must be equal to b
return 0;
});
console.log(example);
【问题讨论】:
-
您的问题是不是要解析的有效日期格式。
-
new Date("1:10am"); //Invalid Date -
我会尝试在 am/pm 后缀前加空格。
标签: javascript sorting date