简体   繁体   中英

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/

if you use new Data(userBooks.data) for comparing array's elements you're good to go. I used.sort method:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM