Home > Software design >  Sort an array of date ranges in typeScript
Sort an array of date ranges in typeScript

Time:10-17

    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" ]

I want to sort this array of date ranges to show the latest date range at the beginning of the array. Having some trouble because the dates are in string format.

CodePudding user response:

Try with this utility function:

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

CodePudding user response:

Array.sort((a, b) => b.localeCompare(a))
  • Related