【问题标题】:lodash orderby with null and real values not ordering correctly具有空值和实值的 lodash orderby 未正确排序
【发布时间】:2016-12-14 09:18:28
【问题描述】:

我有一个 Angular 2 typescript 应用程序,它使用 lodash 处理各种事情。

我有一个对象数组,我正在使用对象中的属性对其进行排序...

_.orderBy(this.myArray, ['propertyName'], ['desc']);

这很好用,但我的问题是有时“propertyName”可能有一个空值。 它们作为降序列表中的第一项排序,然后是最高的实际值。

我想让这些空值按降序排列在最后。

我明白为什么空值排在第一位了。

有人知道如何处理吗?

【问题讨论】:

    标签: javascript typescript lodash


    【解决方案1】:

    _.orderBy() 函数的迭代器可以使用方法而不是字符串。检查值,如果是null,则返回一个空字符串。

    const myArray = [{ propertyName: 'cats' }, { propertyName: null }, { propertyName: 'dogs' }, { propertyName: 'rats' }, { propertyName: null }];
    
    const result = _.orderBy(myArray, ({ propertyName }) => propertyName || '', ['desc']);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

    检查可以很简单(就像我用过的那样),它将所有虚假值转换为空字符串:

    propertyName || ''
    

    如果需要更严格的检查,可以使用三元运算符,只处理null 值:

    propertyName === null ? '' : propertyName
    

    编辑:多重排序示例:

    const result = _.orderBy(myArray, (item) => [get(item, 'propertyName', 0), get(item, 'propertyName2')], ['desc', 'asc']);
    

    这将按propertyName 然后propertyName2 订购。

    如果propertyName 未定义/为空,则其默认顺序将设置为0。 (因此由于descpropertyName 字段上的排序,最终将显示)。在这种情况下,propertyName2 将因此确定排序。

    【讨论】:

    • 非常接近,谢谢。我已经在下面发布了完整的解决方案。
    • 你为什么需要所有额外的东西[( o ) => { return o.myProperty || ''}]?我的解决方案开箱即用。见sn-p。只需将propertyName 替换为属性名称即可。
    • 它对我来说似乎不像你拥有的那样工作,但它确实像我拥有的​​那样。也许它是一个lodash的东西或什么的。无论如何,现在问题已经解决了。感谢您的帮助。
    • 很奇怪。也许打字稿不喜欢它。
    • 这仍然以'asc'顺序对空值进行排序,有没有办法让空值总是在末尾?
    【解决方案2】:

    我需要的代码是这样的……

    _.orderBy(this.myArray, [( o ) => { return o.myProperty || ''}], ['desc']); 
    

    【讨论】:

    • 这仍然按 asc 顺序对空值进行排序,有没有办法让空值总是在末尾?
    • @stallingOne 我知道这是旧的,但对于任何试图实现这一点的人,你可以尝试 _.orderBy(this.myArray, o => o || undefined)
    【解决方案3】:

    为了将来参考其他人,您可以这样做以在末尾使用错误值进行升序排序。

    items =>
      orderBy(
        items,
        [
          i => !!i.attributeToCheck,
          i => {
            return i.attributeToCheck ? i.attributeToCheck.toLowerCase() : ''
          }
        ],
        ['desc', 'asc']
      )
    

    【讨论】:

      【解决方案4】:

      这会将错误的值放在底部,并区分数字和字符串。

      const items = [] // some list
      
      const goodValues = isAscending => ({ value }) => {
          if (typeof value !== 'string' && isNaN(value)) {
              return isAscending ? Infinity : -Infinity
          }
      
          return value || ''
      }
      
      const sortedItems = orderBy(
          items,
          [goodValues(isAscending), 'value'],
          [isAscending ? 'asc' : 'desc']
      )
      

      【讨论】:

        【解决方案5】:

        这对我有用

        orders = [{id : "1", name : "test"}, {id : "1"}];
        sortBy = ["id", "name"];
        orderby(
                    orders,
                    sortBy.map(s => {
                        return (r: any) => {
                            return r[s] ? r[s] : "";
                        };
                    })),
                );
        

        【讨论】:

          【解决方案6】:

          我的看起来像这样。 PropName 和 sort 在我的解决方案中都是变量

          return _.orderBy( myarray, [
            ( data ) => {
              if ( data[propName] === null ) {
                  data[propName] = "";
              }
              return data[propName].toLowerCase();
              }
           ], [sort] );
          

          我想要小写,否则如果不同的大小写,排序是不正确的

          【讨论】:

            【解决方案7】:

            我为此创建了一个函数(ts 代码):

            const orderByFix = (array: any[], orderKeys: string[], orderDirs: ('asc' | 'desc')[]) => {
              const ordered = orderBy(array, orderKeys, orderDirs);
              const withProp = ordered.filter((o) => orderKeys.every(k => o[k]));
              const withoutProp = ordered.filter((o) => !orderKeys.every(k => o[k]));
              return [...withProp, ...withoutProp];
            };
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-12-11
              • 2015-09-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-04-14
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多