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

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

但这不起作用。 你能帮我解决这个问题吗?

最佳答案

由于时间戳已针对字典排序进行标准化,也许您可​​以使用 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/

相关文章:

javascript - React 通过索引管理多维数组

javascript - react : passing in properties

javascript - 使用 Electron 时,设计 HTML/CSS 布局的最佳方式是什么?

javascript - jquery删除表行帮助

javascript - JavaScript 的 trimLeft() 与 trimStart() 之间的区别

javascript - 在 JavaScript 模板引擎中重用元素

javascript - 如何基于Material ui测试组件?

javascript - 检测文件是否已在 JavaScript 中打开

Javascript 排序多维对象

javascript - 如何为 React App 创建防弹构建脚本?