lodash orderby with null and real values not ordering correctly

后端 未结 6 729

I have an Angular 2 typescript application that is using lodash for various things.

I have an array of objects that I am ordering using a property in the object...

6条回答
  •  一生所求
    2021-01-07 22:47

    The _.orderBy() function's iteratees can use a method instead of a string. Check the value, and if it's null return an empty string.

    const myArray = [{ propertyName: 'cats' }, { propertyName: null }, { propertyName: 'dogs' }, { propertyName: 'rats' }, { propertyName: null }];
    
    const result = _.orderBy(myArray, ({ propertyName }) => propertyName || '', ['desc']);
    
    console.log(result);

    The check can be simple (like the one I've used), which converts all falsy values to an empty string:

    propertyName || ''
    

    If you need a stricter check, you can use the ternary operator, and handle just null values:

    propertyName === null ? '' : propertyName
    

    Edit: Example with multiple ordering:

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

    This will order by propertyName then propertyName2.

    If propertyName is undefined/null then its default order will be set to 0. (and therefore will be displayed at last because of desc ordering on the propertyName field). In such case, propertyName2 will therefore determine the ordering.

提交回复
热议问题