2

I'm trying to understand why Array.prototype.sort() doesn't work for date objects:

var x = [new Date("2015-03-16"), new Date("2015-02-24"), new Date("2015-03-13")];
x.sort(); // [Fri Mar 13 2015 01:00:00 GMT+0100 (CET), Mon Mar 16 2015 01:00:00 GMT+0100 (CET), Tue Feb 24 2015 01:00:00 GMT+0100 (CET)]
x[0] <= x[1]; // true
x[1] <= x[2]; // false !!!!!!

I know how I can get them to sort nicely (by using x.sort(function (a, b) {return a - b; });, however I'd like to understand why {both Chrome and Safari} don't sort elements in an array in the order it knows about (when using <)

1
  • Dates are really numbers, so sorting by valueOf is simple. if you compare as strings, then results are not what you want. Commented Mar 22, 2015 at 0:52

2 Answers 2

3

It actually seems that the spec (or at least, what mozilla wites about it) is to blame (my emphasis):

Parameters - compareFunction

Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

Since the string conversion starts with the day of the week, dates will always be sorted alphabetically: Fri, Mon, Sat, Sun, Thu, Tue, Wed....

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

1 Comment

Yes, it's the spec who defines this behavior. See steps 13-18 of the SortCompare abstract operation, in section 15.4.4.11.
0

This solution seems a bit convoluted but if you want to evade passing arguments to the sort method altogether, this should work:

x.map(function (ele) { return ele.valueOf(); }).sort().map(function (ele) { return new Date(ele); });

1 Comment

OP knows how to sort (as numbers), but that doesn't explain the behavior he asked about.

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.