0

The dates look like this:

[‘Oct 7, 2009’, ‘Nov 10, 2009’, ‘Jan 10, 2009’, ‘Oct 22, 2009’, …]

The month is always the first three characters of full month name (‘January’ => ‘Jan’, ‘February’ => ‘Feb’, …).

The day is one or two digits (1, 2, … 31), with no preceding zero.

There is always a comma after the day. The year is always four digits.

I'm trying to write a function that will order this list of string in date by descending order

This is what I have currently:

let dates = [
'Oct 7, 2009',
'Nov 10, 2009',
'Jan 10, 2009',
'Oct 22, 2009'
]

let sortDate = function (date1, date2) {
  if (date1 > date2) return -1
  if (date1 < date2) return 1
  return 0
}

dates.sort(sortDate)

for (let i = 0; i < dates.length; i++) {
  document.write(i + ': ' + dates[i])
}

The output shows this though:

0: Oct 7, 2009
1: Oct 22, 2009
2: Nov 10, 2009
3: Jan 10, 2009

January should be first.

2 Answers 2

2

In your sort callback, return the difference of the dates expressed in epochs (number of milliseconds). You can use Date.parse for this:

    return Date.parse(date1) - Date.parse(date2);

let dates = ['Oct 7, 2009', 'Nov 10, 2009', 'Jan 10, 2009', 'Oct 22, 2009'];

let sortDate = function (date1, date2) {
  return Date.parse(date1) - Date.parse(date2);
}

dates.sort(sortDate)

for (let i = 0; i < dates.length; i++) {
  console.log(i + ': ' + dates[i])
}

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

Comments

1

You're sorting on alphanumeric order not in date order, because you're comparing strings. You need to convert those strings to Date before sorting.

dates.map(date => {
  arr = date.match(/([a-zA-Z]{3}) ([0-9]{1,2}), ([0-9]{4})/);
  return new Date(arr[3], months.indexOf(arr[1]), arr[2]);
});

Where dates is your date array and months is an ordered array of months.

And then in your comparison function compare date.valueOf(), which is the Date represented in milliseconds since Unix epoch

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.