Search code examples
javascriptisodate

Sort by iso string descending isn't working


Desired Behaviour

Sort array of objects by object's iso_string property, descending.

Actual Behaviour

Array order is not changed.

What I've Tried

I must have made a simple error somewhere because multiple posts confirm that is the correct sort() syntax to use.

iso_string value is generated with new Date().toISOString();

var dates = [{
  "formatted_date": "22/09/2018 @ 04:02pm",
  "iso_string": "2018-09-22T06:02:22.485Z"
}, {
  "formatted_date": "22/09/2018 @ 04:12pm",
  "iso_string": "2018-09-22T06:12:04.471Z"
}, {
  "formatted_date": "22/09/2018 @ 04:05pm",
  "iso_string": "2018-09-22T06:05:45.818Z"
}, {
  "formatted_date": "22/09/2018 @ 04:00pm",
  "iso_string": "2018-09-22T06:00:46.954Z"
}, {
  "formatted_date": "22/09/2018 @ 03:56pm",
  "iso_string": "2018-09-22T05:56:13.968Z"
}];

var sorted_dates = dates.sort(function(a, b) {
  return b.iso_string - a.iso_string;
});

console.log(sorted_dates);

Edit: I wrapped values in new Date() and it sorts correctly.


Solution

  • iso_string is in string type you need to convert it into date and then sort. Here is a improved sample

    var dates = [{
      "formatted_date": "22/09/2018 @ 04:02pm",
      "iso_string": "2018-09-22T06:02:22.485Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:12pm",
      "iso_string": "2018-09-22T06:12:04.471Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:05pm",
      "iso_string": "2018-09-22T06:05:45.818Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:00pm",
      "iso_string": "2018-09-22T06:00:46.954Z"
    }, {
      "formatted_date": "22/09/2018 @ 03:56pm",
      "iso_string": "2018-09-22T05:56:13.968Z"
    }];
    var sorted_dates = dates.sort(function(a, b) {
      return new Date(b.iso_string) - new Date(a.iso_string);
    });
    console.log(sorted_dates);

    You can also use localCompare() without converting the string into date.

    var dates = [{
      "formatted_date": "22/09/2018 @ 04:02pm",
      "iso_string": "2018-09-22T06:02:22.485Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:12pm",
      "iso_string": "2018-09-22T06:12:04.471Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:05pm",
      "iso_string": "2018-09-22T06:05:45.818Z"
    }, {
      "formatted_date": "22/09/2018 @ 04:00pm",
      "iso_string": "2018-09-22T06:00:46.954Z"
    }, {
      "formatted_date": "22/09/2018 @ 03:56pm",
      "iso_string": "2018-09-22T05:56:13.968Z"
    }];
    
    var sorted_dates = dates.sort((a, b)=>b.iso_string.localeCompare(a.iso_string));
    console.log(sorted_dates);