簡體   English   中英

如何根據reactjs中日期的降序排序對象數組?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM