按 iso 字符串降序排序不起作用

Sort by iso string descending isn't working

期望的行为

按对象的 iso_string 属性 降序排列对象数组。

实际行为

数组顺序没有改变。

我试过的

我一定是在某个地方犯了一个简单的错误,因为多个帖子确认使用的是正确的 sort() 语法。

iso_string 值由 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);

编辑: 我将值包装在 new Date() 中并且排序正确。

iso_string是string类型,需要转成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(function(a, b) {
  return new Date(b.iso_string) - new Date(a.iso_string);
});
console.log(sorted_dates);

您也可以使用 localCompare() 而不将字符串转换为日期。

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

因为你有 ISO 8601 date which can be sorted lexicographically, you can use string.localCompare() 来排序。

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" }],
    sorted_dates = dates.sort((a, b) => b.iso_string.localeCompare(a.iso_string));

console.log(sorted_dates);
.as-console-wrapper { max-height: 100% !important; top: 0; }