![](/img/trans.png)
[英]ReactJS, How to get the oldest and newest date from array using moment.js
[英]How to sort by oldest and newest using date?
我有一个这样的演示文稿,当然,有更多的书,我想根据最旧和最新的书籍对书籍进行排序,我应该怎么做?
const userBooks = [
{
id: 1,
name: "",
author: "",
genre: "",
date: "2022-1-12",
},
{
id: 2,
name: "",
author: "",
genre: "",
date: "2022-2-8",
},
];
您可以这样做以按日期降序对其进行排序:
let descending = userBooks.sort((x,y) => new Date(y.date) - new Date(x.date))
或按日期升序:
let ascending = userBooks.sort((x,y) => new Date(x.date) - new Date(y.date))
首先使用 javascript 日期 function 保存日期并考虑此页面https://stackabuse.com/how-to-sort-an-array-by-date-in-
如果您使用新数据(userBooks.data)来比较数组的元素,那么您对 go 很好。 我使用了.sort 方法:
let sortedUserBooks = userBooks.sort((a, b) => {
return new Date(a.date) - new Date(b.date)
})
console.log(sortedUserBooks)
这是结果:
[
{ id: 3, name: '', author: '', genre: '', date: '2022-1-5' },
{ id: 1, name: '', author: '', genre: '', date: '2022-1-12' },
{ id: 2, name: '', author: '', genre: '', date: '2022-2-8' }
]
我添加了第三个 object 来检查它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.