![](/img/trans.png)
[英]How to sort array based on date in descending order if value exists in JS?
[英]How to sort array of objects based on descending order of date in reactjs?
我有一個如下所示的對象數組,並希望按降序排序。
下面是對象數組
[
{
"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});
但這不起作用。 你能幫我一個人嗎?
更換
(a, b) => a.timestamp - b.timestamp
同
(a, b) => a.timestamp.valueOf() - b.timestamp.valueOf()
(如果timestamp
確實是Date對象的話。)
您可以創建每個時間戳的日期對象並進行比較
const data = [ { "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", }, ] console.log(data.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp)));
由於timestamps
是針對詞典排序規范化的,也許你可以在sort
方法上使用String.localeCompare() :
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.