如何按最后一个为空的多个日期时间属性排序?

How to order by multiple date time properties with nulls last?

我有一个 json,我想按多个日期时间属性对这个 json 进行排序。但是有一个 pinnedAt 属性 指出 post 必须在最上面。顺便说一句,我正在使用 lodash。

这是我要解释的 sql 文档:

If NULLS LAST is specified, null values sort after all non-null values; if NULLS FIRST is specified, null values sort before all non-null values. If neither is specified, the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified (thus, the default is to act as though nulls are larger than non-nulls). When USING is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator.

您可以在这里阅读更多内容:https://www.postgresql.org/docs/9.0/static/sql-select.html


这是我的示例数据:

{
  "data": [
    {
      "name": "Paris",
      "createdAt": "2018-10-01T08:28:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "New York",
      "createdAt": "2018-10-01T05:16:05.074Z",
      "pinnedAt": null
    },
     {
      "name": "Washington",
      "createdAt": "2018-10-02T08:28:05.074Z",
      "pinnedAt": "2018-10-02T15:19:23.245Z"
    }
  ]
}

我要订购的代码

posts = _.orderBy(state.posts, ['pinnedAt', 'createdAt'], ['desc', 'desc']);

但这并不像我想要的那样。这是我所期望的

{
  "data": [
    {
      "name": "Washington",
      "createdAt": "2018-10-02T08:28:05.074Z",
      "pinnedAt": "2018-10-02T15:19:23.245Z"
    },
    {
      "name": "Paris",
      "createdAt": "2018-10-01T08:28:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "New York",
      "createdAt": "2018-10-01T05:16:05.074Z",
      "pinnedAt": null
    }
  ]
}

我该怎么做?

谢谢。

您可以使用自定义函数将 null 视为将正确排序的不同值。

const data = [
    {
      "name": "Paris",
      "createdAt": "2018-10-01T08:28:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "New York",
      "createdAt": "2018-10-01T05:16:05.074Z",
      "pinnedAt": null
    },
    {
      "name": "Washington",
      "createdAt": "2018-10-02T08:28:05.074Z",
      "pinnedAt": "2018-10-02T15:19:23.245Z"
    }
]; 

const result = _.orderBy(data, 
                         [(item) => item.pinnedAt ? item.pinnedAt : "", 'createdAt'], 
                         ['desc', 'desc']);

使用 lodash 的 4.17.11 版使用 https://npm.runkit.com/lodash

进行测试

这是有效的,因为空字符串是 "less than" 任何其他字符串值。降序排序时,这将始终显示在列表的末尾。因为这些空字符串值是等价的,没有 pinnedAt 的对象将按预期根据 createdAt 排序。