Home > database >  How to sort this data in order of current month and current day should come first in chronological o
How to sort this data in order of current month and current day should come first in chronological o

Time:10-21

[ { data:"Jan 12", year:2020 }, { data:"Jan 12", year:2021 }, { data:"Jan 5", year:2020 }, { data:"Oct 12", year:2021 }, { data:"Oct 12", year:2022 } ]

CodePudding user response:

If the sort was only by the year, it would be easy:

const data = [
  { data: "Jan 12", year: 2020 },
  { data: "Jan 12", year: 2021 },
  { data: "Jan 5", year: 2020 },
  { data: "Oct 12", year: 2021 },
  { data: "Oct 12", year: 2022 },
];

const sortedDates = data.sort((a, b) => a.year - b.year);

But how would be the sorting by mont and day ?, could you be more specific, or add some examples please ?

CodePudding user response:

I would probably just cast the object as a date using a string since it seems to be what you almost have here. I'm not sure how it is in terms of performances but here is a solution that could work:

let dates = [ 
  { data:"Jan 12", year:2020 }, 
  { data:"Jan 12", year:2021 }, 
  { data:"Jan 5", year:2020 }, 
  { data:"Oct 12", year:2021 }, 
  { data:"Oct 12", year:2022 } 
]

dates.sort((a,b) => {
  let aDate = new Date(`${a.data} ${a.year}`) 
  let bDate = new Date(`${b.data} ${b.year}`)
  if(aDate < bDate)
    return 1;
  if(aDate > bDate)
    return -1
  return 0
})
  • Related