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.

5
  • You should make new Date() out of your strings Commented Aug 29, 2017 at 14:20
  • b/c javasciprt don't understand your string as date, see sort-javascript-object-array-by-date Commented Aug 29, 2017 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... Commented Aug 29, 2017 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. Commented Aug 29, 2017 at 14:28
  • @spanky you could be correct, although I think your approach of using localeCompare() is better :) Commented Aug 29, 2017 at 14:31

2 Answers 2

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.

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

Comments

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

1 Comment

I'm so accustomed to using .localeCompare() that I forget the default .sort() is alphabetical. Using .sort() alone here is nicer.

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.