0

I am trying to implement a date-sorting method for a news list that works across browsers. However, the one method I have tried that works well, only works in Chrome:

 origArt.sort(function(a, b) {
      var dateA = new Date(a.date), dateB = new Date(b.date);
                        return dateB - dateA;
                              });

I also tried this code, suggested in other sorting questions as a possible solution:

origArt.sort(function(a,b){
        return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
                          });

But, because the dates in my JSON vary from year; month & year; and month, year and day; the news list sorts in reverse alphabetical order, not reverse chronological order.

Rgreaner
  • 31
  • 12
  • What are some examples of the variables `a` and `b`? Are they strings with formats "2000", "12/2000", "12/1/2000"? – Matt Jan 29 '19 at 00:38
  • Your first one seems like it should work. What happens when you try it in other browsers? – John Montgomery Jan 29 '19 at 00:38
  • They are strings such as: "2018.", "April 8, 2015.", and "September 2015." @JohnMontgomery --In Safari and Firefox the list is output based on the order the items are in the JSON file. – Rgreaner Jan 29 '19 at 00:47

1 Answers1

0

They are strings such as: "2018.", "April 8, 2015.", and "September 2015."

Your problem is that those aren't valid date strings. From some quick testing, Chrome appears to be doing a bit of guesswork as to what you mean, but the other browsers aren't.

Chrome:

new Date("2018.")
// Mon Jan 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)

Firefox:

new Date("2018.")
// Invalid Date

And since Invalid Date > Invalid Date is always false, it isn't sorting anything. It's not just a matter of removing the period either, since "September 2015" also works in Chrome but fails in Firefox.

Ideally, you should fix your JSON or whatever code it's being generated from to use parseable date strings. If that's not an option, you'll probably have to write a custom parsing function that handles all the possible formats you might get, or see if a library like Moment.js can handle it for you.

John Montgomery
  • 6,739
  • 9
  • 52
  • 68
  • Ok, it's not ideal to have the JSON a specific way, but that seems to be the best way to solve my problem. Do you know if there is a specific/best format for the JSON data to work across all browsers? – Rgreaner Jan 29 '19 at 01:49
  • https://stackoverflow.com/questions/10286204/the-right-json-date-format – John Montgomery Jan 29 '19 at 01:52