Array(6) [
"10-2022 - 12-2022",
"08-2022 - 09-2022",
"07-2023 - 10-2023",
"04-2022 - 07-2022",
"01-2023 - 06-2023",
"01-2022 - 03-2022" ]
我想對這個日期范圍陣列進行排序,以在陣列的開頭顯示最新的日期范圍。有一些麻煩,因為日期是字串格式。
uj5u.com熱心網友回復:
試試這個實用功能:
const arr = [
"10-2022 - 12-2022",
"08-2022 - 09-2022",
"07-2023 - 10-2023",
"07-2023 - 11-2023",
"04-2022 - 07-2022",
"01-2023 - 06-2023",
"01-2022 - 03-2022"
];
const getYearMonth = (date) => {
const dateSplit = date.split('-');
if (dateSplit.length < 2) return '';
return dateSplit[1] '-' dateSplit[0];
}
const sortedArr = arr.sort((a, b) => {
const aSplit = a.split(' - ');
const bSplit = b.split(' - ');
const aYearMonthStart = getYearMonth(aSplit[0]);
const bYearMonthStart = getYearMonth(bSplit[0]);
// Sort decreasing by start
if (aYearMonthStart > bYearMonthStart) return -1;
if (aYearMonthStart < bYearMonthStart) return 1;
// Sort decreasing by end date if start date equal
const aYearMonthEnd = getYearMonth(aSplit[1]);
const bYearMonthEnd = getYearMonth(bSplit[1]);
if (aYearMonthEnd > bYearMonthEnd) return -1;
if (aYearMonthEnd < bYearMonthEnd) return 1;
// Equal dates
return 0;
})
console.log(sortedArr);
uj5u.com熱心網友回復:
Array.sort((a, b) => b.localeCompare(a))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515573.html
標籤:反应打字稿
上一篇:對于打字稿,如何在類中定義介面
