Sometimes, we want to do a case insensitive sorting on a collection using Lodash orderBy with JavaScript.
In this article, we’ll look at how to do a case insensitive sorting on a collection using Lodash orderBy with JavaScript.
How to do a case insensitive sorting on a collection using Lodash orderBy with JavaScript?
To do a case insensitive sorting on a collection using Lodash orderBy with JavaScript, we can convert all the values to lower case before we compare them with orderBy
.
For instance, we write
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);
to call orderBy
with the users
array, an array with a function that convert each object’s name
property to lower case, and an array with the order that we want to sort by.
We convert each name
property to lower case with the toLowerCase
method.
A new array with the sorted values is returned.
Conclusion
To do a case insensitive sorting on a collection using Lodash orderBy with JavaScript, we can convert all the values to lower case before we compare them with orderBy
.