1

I can't get this sorted by relevantDate. I need newest date first. Can you please help me? Thanks a lot in anticipation!

publications = [{
    "publicationDate" : "12.05.2022",
    "relevantDate" : "01.06.2022",
    "title" : "Bücher",
    "type" : "allgemein"
  }, {
    "publicationDate" : "04.05.2022",
    "relevantDate" : "21.05.2022",
    "title" : "Videos",
    "type" : "allgemein"
  }, {
    "publicationDate" : "14.04.2022",
    "relevantDate" : "25.05.2022",
    "title" : "Musik",
    "type" : "allgemein"
  }];


     publications.sort(function(a, b){
     return new Date(a.relevantDate) - new Date(b.relevantDate);
     });
3
  • You need to parse that date manually, just passing it to the Date constructor will not be reliable. There are plenty of examples of doing this on SO Commented May 12, 2022 at 13:58
  • 3
    I was in the process of supplying an answer this so that the requester could understand where their issue lay but the question was closed. I will briefly say that the format your dates are arriving in are not one that the Date object constructor understands. I would recommend if you have any control over the API to get the dates sent in a recognised ISO format. Failing that you can string manipulate them into something that the date constructor will accept. Something like this might work, but I would check it works in all cases! new Date("14.04.2022".split('.').reverse().join()) Commented May 12, 2022 at 14:03
  • Thank you very much, Glenn! This is great :-) It works: return new Date(a.relevantDate.split('.').reverse().join()).getTime() - new Date(b.relevantDate.split('.').reverse().join()).getTime(); or just return new Date(a.relevantDate.split('.').reverse().join()) - new Date(b.relevantDate.split('.').reverse().join()); Commented May 12, 2022 at 14:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.