0
    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.

2
  • 1
    What have you tried so far? Array.sort can take a compare function as a parameter so you need to implement one which works with your input. Also, be aware that Array.sort mutates the array, which will make you run into problems with React if you don't make a copy beforehand. Commented Oct 17, 2022 at 6:14
  • I tried Array.sort but had no luck. I think its because it takes a range of dates as the argument ` "10-2022 - 12-2022"` . Commented Oct 17, 2022 at 6:32

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

-1
Array.sort((a, b) => b.localeCompare(a))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.