javascriptnode.jsdateecmascript-5

ES5 sort() and dates


I have a number of objects in an array. The objects have a 'time' property which is a date string.

items = [
  {time: "2013-03-01T10:46:11Z"},
  {time: "2013-03-03T10:46:11Z"},
  {time: "2013-03-02T10:46:11Z"}
]

I wish to sort the array by that 'time' property.

I've read How to sort an object array by date property? and Javascript Date Sorting, but I can't seem to make either of these solutions (either converting to Date objects or sorting as strings) work.

My sort function:

items.sort(function(first, second){
  return new Date(first.time) < new Date(second.time) ? 1 : -1;
})

Testing the results:

items.forEach(function(item){
  console.log(item.time)
})

Returns:

2013-03-01T10:46:11Z
2013-03-03T10:46:11Z
2013-03-02T10:46:11Z

March 1, March 3, March 2. What am I doing wrong?


Solution

  • You're calling the field "date" instead of "time" in your comparator function. Also, the function should return an integer, not a boolean:

      return new Date(first.time) - new Date(second.time);
    

    That may not work in all browsers. If all your times are Universal Time, just compare them as strings:

      return first.time > second.time ? 1 : first.time === second.time ? 0 : -1;