How do I sort these descending correctly? I've tried arr.sort() arr.sort().reverse() , looked all over stack overflow ... and I cannot find a way to do this. Everything tries to sort them but does it wrong.
[
'1/19/2024', '1/20/2023',
'10/21/2022', '11/18/2022',
'12/16/2022', '3/17/2023',
'6/10/2022', '6/16/2023',
'6/17/2022', '6/21/2024',
'6/24/2022', '6/3/2022',
'6/31/2022', '7/15/2022',
'7/8/2022', '8/19/2022',
'9/15/2023', '9/16/2022'
]
Then I need to take those and turn them into the actual month. Jan, Feb, etc. instead of the numerical value ...
So, easiest way is to convert strings to dates, sort it and then convert dates to string format back, see:
const origArr = [
'1/19/2024', '1/20/2023',
'10/21/2022', '11/18/2022',
'12/16/2022', '3/17/2023',
'6/10/2022', '6/16/2023',
'6/17/2022', '6/21/2024',
'6/24/2022', '6/3/2022',
'6/31/2022', '7/15/2022',
'7/8/2022', '8/19/2022',
'9/15/2023', '9/16/2022'
];
// create array of dates
const datesArr = origArr.map(str => new Date(str));
// sort array of dates
const datesSortedArr = datesArr.sort((a,b) => b - a);
// convert dates to strings
const sortedArr = datesSortedArr.map(item => {
const month = item.getMonth() + 1;
const day = item.getDate();
const year = item.getFullYear();
return `${month}/${day}/${year}`;
});
console.log('sortedArr:', sortedArr);
you can convert them to Date order them and than convert them back to the original format
const dates = [
'1/19/2024', '1/20/2023',
'10/21/2022', '11/18/2022',
'12/16/2022', '3/17/2023',
'6/10/2022', '6/16/2023',
'6/17/2022', '6/21/2024',
'6/24/2022', '6/3/2022',
'6/31/2022', '7/15/2022',
'7/8/2022', '8/19/2022',
'9/15/2023', '9/16/2022'
]
const toDate = string => {
const [month, day, year] = string.split('/')
return new Date([year, month.padStart(2, '0'), day.padStart(2, '0')].join('-'))
}
const toString = date => [date.getMonth() + 1, date.getDate(), date.getFullYear()].join('/')
const reorder = data => {
const dates = data.map(toDate)
dates.sort((a, b) => b - a)
return dates.map(toString)
}
console.log(reorder(dates))