Claude
Claude

Reputation: 9990

Array.sort() not working for date objects

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

Upvotes: 2

Views: 363

Answers (2)

Mr. X
Mr. X

Reputation: 274

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

Upvotes: 0

Claude
Claude

Reputation: 9990

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....

Upvotes: 3

Related Questions