我们有这样的对象数组:
{key: "T62", currentWinnerName: "Test Register", dateCreated: Fri Jan 18 2019 18:17:50 GMT+0000 (Greenwich Mean Time)}
{key: "T68", currentWinnerName: "Test Register", dateCreated: Wed Jan 23 2019 14:57:40 GMT+0000 (Greenwich Mean Time)}
{key: "T58", currentWinnerName: "Test Register", dateCreated: Fri Jan 18 2019 15:57:45 GMT+0000 (Greenwich Mean Time)}
我们需要根据数组中的dateCreated
值对数组进行排序。
我已经尝试了各种排序方法,但无法更改顺序。
如果我
理解正确,你的对象是数组。 然后你可以这样做。
var obj = [
{
key: "T62",
currentWinnerName: "Test Register",
dateCreated: "Fri Jan 18 2019 18:17:50 GMT+0000 (Greenwich Mean Time)"
},
{
key: "T68",
currentWinnerName: "Test Register",
dateCreated: "Wed Jan 23 2019 14:57:40 GMT+0000 (Greenwich Mean Time)"
},
{
key: "T58",
currentWinnerName: "Test Register",
dateCreated: "Fri Jan 18 2019 15:57:45 GMT+0000 (Greenwich Mean Time)"}
];
let sortedObj = obj.sort(function(a,b){
return new Date(b.dateCreated) - new Date(a.dateCreated);
});
console.log(sortedObj);
你有没有试过这样的事情:
const getTimestamp = (dateString)=> new Date(dateString).getTime();
const isOlder = (object1, object2)=> getTimestamp(object1.dateCreated) < getTimestamp(object2.dateCreated) ? -1 : 1;
const sortedArr = arr.sort(isOlder);
arr
是您的阵列。但是你必须把dateCreated
变成一个字符串。这对我有用。