如何在reactjs中根据日期的降序对对象数组进行排序?

时间:2019-04-05 15:44:00

标签: javascript 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});

但这不起作用。 有人可以帮我吗?

3 个答案:

答案 0 :(得分:0)

替换

(a, b) => a.timestamp - b.timestamp

使用

(a, b) => a.timestamp.valueOf() - b.timestamp.valueOf()

(如果timestamp确实是Date对象。)

答案 1 :(得分:0)

您可以创建每个时间戳的日期对象并进行比较

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)));

答案 2 :(得分:0)

由于对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));
相关问题