Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date sort in JS where the array of objects has the word "week" in it

list of dates

How does one begin to sort this? I could not find something similar online.
I have tried to sort by length but that made it even more of a mess like so:

dateButtons.sort((a,b) => {
  return b.text.length - a.text.length
})

where as "text" is equal to the date string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the sort method and split year and month in the compare function:

const dates = ['2020 week 2', '1999 week 32', '2021 week 20', '2020 week 4', '2020 week 1'];

console.log(dates.sort((lhs, rhs) => {
  const [lyear, lweek] = lhs.split(' week ');
  const [ryear, rweek] = rhs.split(' week ');
  return lyear - ryear || lweek - rweek;
}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading