我有一个如下所示的对象数组,并希望按降序对其进行排序。
下面是对象数组
[
{
"attributes": {
},
"timestamp": "2019-04-03T21:00:00+00:00",
},
{
"attributes": {
},
"timestamp": "2019-04-03T09:24:27.179190+00:00",
},
{
"attributes": {
},
"timestamp": "2019-04-03T08:54:06.721557+00:00",
},
{
"attributes": {
},
"timestamp": "2019-04-03T04:54:56.227415+00:00",
},
]
我尝试了什么?
let sorted_array = this.state.array.sort((a, b) => a.timestamp -
b.timestamp);
this.setState({array: sorted_array});
但这不起作用。 你能帮我解决这个问题吗?
最佳答案
由于时间戳
已针对字典排序进行标准化,也许您可以使用 String.localeCompare()在 sort
方法上:
let input = [
{
"attributes": {},
"timestamp": "2019-04-03T21:00:00+00:00",
},
{
"attributes": {},
"timestamp": "2019-04-03T09:24:27.179190+00:00",
},
{
"attributes": {},
"timestamp": "2019-04-03T08:54:06.721557+00:00",
},
{
"attributes": {},
"timestamp": "2019-04-03T04:54:56.227415+00:00",
}
];
input.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
console.log(input);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
如果需要按升序排序,则使用:
input.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
关于javascript - 如何在reactjs中根据日期降序对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55539108/