When using the orderBy function from Lodash to sort a collection, achieving case-insensitive sorting can be done by providing a custom iterator function that converts each element to a consistent case (typically lowercase or uppercase), followed by the sorting operation. This ensures consistent comparison regardless of the original string's case.
Here's a concrete example. Suppose we have an array of user objects, and we want to sort them case-insensitively by the username property (username):
javascriptimport _ from 'lodash'; const users = [ { 'user': 'fred', 'age': 48 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'Barney', 'age': 34 } ]; // Use orderBy for sorting, with an iterator function converting all usernames to lowercase const sortedUsers = _.orderBy(users, [(user) => user.user.toLowerCase()], ['asc']); console.log(sortedUsers);
In the above code, the second parameter of orderBy is an array containing the iterator function. The function user => user.user.toLowerCase() converts the user property (i.e., the username) to lowercase, ensuring consistent comparison even when original usernames have inconsistent casing.
The third parameter ['asc'] specifies the sorting order as ascending. For descending order, replace it with ['desc'].
This approach will sort the sortedUsers array case-insensitively by username.