0

I have an array of dates $myArray

(2012-09-31,1999-01-23,2018-08-29,1808-04-20,2017-11-05,1001-10-01,)

I want to list these dates in most current to oldest, i am using a function

function myFunction() {
myArray.sort(function(a, b){return b-a});
}

The above function does not seem to order the array in any particular way.

jumpman8947
  • 571
  • 1
  • 11
  • 34
  • You should make `new Date()` out of your strings – kevinSpaceyIsKeyserSöze Aug 29 '17 at 14:20
  • b/c javasciprt don't understand your string as date, see [sort-javascript-object-array-by-date](https://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date) – aahhaa Aug 29 '17 at 14:20
  • We can't help you based on what's in the question, as we have no idea what's in your array. Date instances? Strings? If it were Date instances, `b-a` would work, so... – T.J. Crowder Aug 29 '17 at 14:21
  • 2
    @Rory, your deleted answer was correct. I think the commenter was omitting `new` from the `Date` calls, which would cause a different result. – spanky Aug 29 '17 at 14:28
  • @spanky you could be correct, although I think your approach of using `localeCompare()` is better :) – Rory McCrossan Aug 29 '17 at 14:31

2 Answers2

4

In this particular case, you can actually use .localeCompare() to do the comparison.

The reason is that your date strings are formatted to be most general to most specific, and are all the same length.

var myArray = ['2012-09-31', '1999-01-23', '2018-08-29', '1808-04-20', '2017-11-05', '1001-10-01'];

function myFunction() {
  myArray.sort(function(a, b) {
    return b.localeCompare(a);
  });
}

myFunction();

console.log(myArray);

This would not work if the leading 0 on a month or day could be removed, or if the format was for example yyyy-dd-mm or mm-dd-yyyy.

spanky
  • 2,768
  • 8
  • 9
3

You can use sort() without any parameters as it will order it alphabetically which work with this time format and then reverse it :

var list = ['2012-09-31', '1999-01-23', '2018-08-29' , '1808-04-20', '2017-11-05', '1001-10-01'];

console.log(list.sort().reverse());
Serge K.
  • 5,303
  • 1
  • 20
  • 27
  • 1
    I'm so accustomed to using `.localeCompare()` that I forget the default `.sort()` is alphabetical. Using `.sort()` alone here is nicer. – spanky Aug 29 '17 at 14:39