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
>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);