Lodash : how to do a case insensitive sorting on a collection using orderBy?
The documentation specifies that you can pass a function as "iteratee":
[iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]): The iteratees to sort by.
So you can do
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 40 },
{ name: 'a', age: 36 }
];
const sortedUsers = _.orderBy(users, [user => user.name.toLowerCase()], ['desc']);
console.log(sortedUsers);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Ordering by multiple properties:
const users = [
{ name: 'A', age: 48 },
{ name: 'B', age: 34 },
{ name: 'b', age: 40 },
{ name: 'a', age: 36 }
]
const nameSorter = user => user.name.toLowerCase()
const ageSorter = 'age'
const sortedUsers = _.orderBy(users, [nameSorter, ageSorter], ['desc', 'asc'])
You can combine Felix Kling example with _.get function to sort by dynamic nested attributes:
const _ = require('lodash');
let test = [{ a: {b:'AA'}},{a: {b:'BB'} }, {a: {b: 'bb'}}, {a:{b:'aa'}}];
let attrPath = 'a.b';
_.orderBy(test, [item => _.get(item, attrPath).toLowerCase()]);