代码之家  ›  专栏  ›  技术社区  ›  ccoeder

如何按上次为空的多个日期时间属性排序?

  •  0
  • ccoeder  · 技术社区  · 7 年前

    这是我试图解释的sql文档:

    如果指定了NULLS LAST,空值在所有非空值之后排序;如果先指定null,则null值将在所有非null值之前排序。如果两者都未指定,则在指定ASC或隐含ASC时,默认行为是最后为null,在指定DESC时,默认行为是首先为null(因此,默认行为是将null视为大于非null)。指定USING时,默认的nulls顺序取决于运算符是小于还是大于运算符。

    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
        }
      ]
    }
    

    我该怎么做?

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Vlad274    7 年前

    您可以使用自定义函数来处理 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


    这是因为空字符串“小于”任何其他字符串值。当按降序排序时,它总是显示在列表的末尾。因为这些空字符串值是等价的,所以没有 pinnedAt createdAt ,如预期。