我有一个像这样的对象数组:
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
价值。
我已尝试申请这个解决方案 https://stackoverflow.com/a/17064665/1063287这是用于字符串值数组的:
example.sort(function (a, b) {
return new Date('1970/01/01 ' + a.time) - new Date('1970/01/01 ' + b.time);
});
console.log(example);
我也提到过 MozillaArray.prototype.sort() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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);