【问题标题】:Sorting an array by multiple properties including date按包括日期在内的多个属性对数组进行排序
【发布时间】:2021-02-16 14:19:11
【问题描述】:

我想按枚举对数组进行排序,然后按数字排序,然后按日期排序。当我使用枚举和数字执行此操作时,它似乎工作正常,但是当我在末尾包含日期时,它会弄乱一切。

这是我的代码:

enum myType { 
  high,
  medium,
  low
}

myArray.sort((a, b) =>
  myType[a.type] - myType[b.type] ||
  a.classification - b.classification ||
  new Date(a.time) > new Date(b.time)
    ? -1
    : 1
);

然而,这似乎排序相反的意思,它按类型以相反的顺序排序,低在前,高在后。我们该怎么做?

更新:日期将按以下方式传递:2017-07-02T14:59:55.711Z

【问题讨论】:

  • 请添加日期样式。

标签: javascript arrays typescript


【解决方案1】:

在不知道time的样式的情况下,需要将三进制包裹起来,防止读取到三进制的所有表达式。

myArray.sort((a, b) =>
    myType[a.type] - myType[b.type] ||
    a.classification - b.classification ||
    (new Date(a.time) > new Date(b.time)
        ? -1
        : 1)
);

通过使用符合ISO 8601 的字符串,您可以与String#localeCompare 进行字符串比较。

myArray.sort((a, b) =>
    myType[a.type] - myType[b.type] ||
    a.classification - b.classification ||
    a.time.localeCompare(b.time)
);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 2016-08-20
  • 1970-01-01
  • 2018-02-09
  • 2016-10-31
相关资源
最近更新 更多