简体   繁体   English

如何按最旧和最新的使用日期排序?

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

相关问题 ReactJS,如何使用 moment.js 从数组中获取最旧和最新的日期 - ReactJS, How to get the oldest and newest date from array using moment.js 使用 VueFire,我如何按日期降序排列我的列表(从最新到最旧)? - Using VueFire, how do I order my list by date in descending order (newest to oldest)? 如何按最新到最旧的 id 值对 JSON 进行排序 - How to sort JSON by id's values newest to oldest 如何按降序顺序按日期对这个项目数组进行排序(我使用了 loadash sortBy 但它首先返回最旧的,而我首先需要最新的)? - How sort this array of items by date in desc order (I used loadash sortBy but it returns oldest first while I need newest first)? 如何将日期表单排序为对象数组中最新到最旧的反应js - How to sort the date form to latest to the oldest in array of objects react js 使用日期,按照日期,按时间顺序对JSON进行排序,最新的优先 - Sort JSON in chronological order according to date, newest first, using jquery 如何使用 select (JavaScript) 将图像从最旧到最新排列然后再返回? - How to arrange images from oldest to newest and then back again using select (JavaScript)? 选择最新/最旧的元素 - Select newest/oldest element 如何按最新和最老的方式对moment.js进行排序? - how to do sorting in moment.js by newest and oldest? 按最新日期按对象数组排序不起作用 - Sort by array of objects by newest date does not work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM