skip to Main Content

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

4

Answers


  1. How the Date constructor parses such strings should not be relied on. Instead construct strings you can order lexically, or their numeric equivalent. Here I rearrange the numeric parts to create one big number (yyyymmdd) and then it works:

    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) => {
        // Extract the numeric parts and rejoin them in the propper order
        const dateA = a.clmFirstReceivedDt.replace(/(..)/(..)/(.*)/, "$3$2$1");
        const dateB = b.clmFirstReceivedDt.replace(/(..)/(..)/(.*)/, "$3$2$1");
        return dateB - dateA; // for descending order
    });
    
    console.log(array);
    Login or Signup to reply.
  2. There you go, if you want to sort the dates which are in the dd/mm/yy format ->

    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"}
    ];
    
    function compareDatesDescending(a, b) {
        const dateA = a.clmFirstReceivedDt.split('/').reverse().join('/');
        const dateB = b.clmFirstReceivedDt.split('/').reverse().join('/');
        if (dateA < dateB) {
            return 1;
        } else if (dateA > dateB) {
            return -1;
        } else {
            return 0;
        }
    }
    
    array.sort(compareDatesDescending);
    console.log(array);
    

    hope this helps 🙂

    Login or Signup to reply.
  3. 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);
    Login or Signup to reply.
  4. Point to noted: Javascript only accept dates format YYYY-MM-DD or MM-DD-DD. You must specify format first which format you are using, if you are using other than above two you should update your format first in your logic than sort the array. Like this

    function sortDatesArr(arr,format){
      if(format === "DD-MM-YYY"){
          arr.map(item =>{
              let itm = item.split('/')
              let tempval1 = itm.pop()
              let tempval2 = itm.shift()
              itm.push(tempval2)
              itm.unshift(tempval1)
              return itm.join('/')
          }).sort((a, b) => {
            const dateA = new Date(a.clmFirstReceivedDt).getTime();
            const dateB = new Date(b.clmFirstReceivedDt).getTime();
            return dateB - dateA;
          });
      }else{
          arr.sort((a, b) => {
            const dateA = new Date(a.clmFirstReceivedDt).getTime();
            const dateB = new Date(b.clmFirstReceivedDt).getTime();
            return dateB - dateA;
          });
      }
      return arr
    }
    print(sortDatesArr(array,'DD-MM-YYY'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search