[英]How to sort by oldest and newest using date?
I have a presentation like this, of course, with more books, I want to sort the books based on the oldest and newest, how should I do this?我有一个这样的演示文稿,当然,有更多的书,我想根据最旧和最新的书籍对书籍进行排序,我应该怎么做?
const userBooks = [
{
id: 1,
name: "",
author: "",
genre: "",
date: "2022-1-12",
},
{
id: 2,
name: "",
author: "",
genre: "",
date: "2022-2-8",
},
];
You can do this to sort it by date descending:您可以这样做以按日期降序对其进行排序:
let descending = userBooks.sort((x,y) => new Date(y.date) - new Date(x.date))
or by date ascending:或按日期升序:
let ascending = userBooks.sort((x,y) => new Date(x.date) - new Date(y.date))
firstly save the date using javascript date function and consider this page https://stackabuse.com/how-to-sort-an-array-by-date-in-javascript/首先使用 javascript 日期 function 保存日期并考虑此页面https://stackabuse.com/how-to-sort-an-array-by-date-in-
if you use new Data(userBooks.data) for comparing array's elements you're good to go.如果您使用新数据(userBooks.data)来比较数组的元素,那么您对 go 很好。 I used.sort method:
我使用了.sort 方法:
let sortedUserBooks = userBooks.sort((a, b) => {
return new Date(a.date) - new Date(b.date)
})
console.log(sortedUserBooks)
and here is result:这是结果:
[
{ 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' }
]
I added third object to check if it works.我添加了第三个 object 来检查它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.