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...>
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 to0
. (and therefore will be displayed at last because ofdesc
ordering on thepropertyName
field). In such case,propertyName2
will therefore determine the ordering.