Home > Back-end >  How to sort by oldest and newest using date?
How to sort by oldest and newest using date?

Time:07-26

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",
  },
];

CodePudding user response:

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))

CodePudding user response:

firstly save the date using javascript date function and consider this page https://stackabuse.com/how-to-sort-an-array-by-date-in-javascript/

CodePudding user response:

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.

  • Related