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

How to sort the array which is in date format latest record on top using javascript

I am having an array

let array = [
  {clmFirstReceivedDt: "16/03/2023"},
  {clmFirstReceivedDt: "17/03/2022"},
  {clmFirstReceivedDt: "13/04/2024"},
  {clmFirstReceivedDt: "06/03/2024"},
  {clmFirstReceivedDt: "06/02/2024"},
  {clmFirstReceivedDt: "12/03/2024"}
];

I am having the date in the day, month, year format when i try

array.sort((a, b) => {
      const dateA = new Date(a.clmFirstReceivedDt).getTime();
      const dateB = new Date(b.clmFirstReceivedDt).getTime();
      return dateB - dateA;
    });

when the format is month, day, year its working fine but when the date format is changed then order is not getting sorted properly

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 :

To ensure proper sorting regardless of the date format, you should parse the date string manually before creating the Date object. You can achieve this by splitting the date string and creating a new Date object with the year, month, and day in the correct order.

let array = [
  {clmFirstReceivedDt: "16/03/2023"},
  {clmFirstReceivedDt: "17/03/2022"},
  {clmFirstReceivedDt: "13/04/2024"},
  {clmFirstReceivedDt: "06/03/2024"},
  {clmFirstReceivedDt: "06/02/2024"},
  {clmFirstReceivedDt: "12/03/2024"}
];

array.sort((a, b) => {
  const getDateFromString = (dateString) => {
    const [day, month, year] = dateString.split('/');
    return new Date(`${year}-${month}-${day}`).getTime();
  };

  const dateA = getDateFromString(a.clmFirstReceivedDt);
  const dateB = getDateFromString(b.clmFirstReceivedDt);
  
  return dateB - dateA;
});

console.log(array);
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