0

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 Sort Javascript Object Array By Date and Javascript Date Sorting, but I can't seem to make either of these solutions (either converting to Date objets 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?

Community
  • 1
  • 1
mikemaccana
  • 81,787
  • 73
  • 317
  • 396

1 Answers1

1

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;
Pointy
  • 371,531
  • 55
  • 528
  • 584
  • Thanks for your answer. I've fixed the demo to use consistent names (and return -1 per Array.sort() docs). Edit: I see the problem is solved. – mikemaccana Mar 06 '13 at 17:17