Sorting Directions in Lodash orderBy
This article explains the sorting directions available in Lodash's
_.orderBy function, detailing how to sort collections in
JavaScript. You will learn the specific direction values supported by
the function, the default behavior when directions are omitted, and how
to apply multi-criteria sorting using contrasting directions.
Supported Sorting Directions
In the Lodash library, the _.orderBy method accepts two
specific string values to determine the sort order:
'asc': Sorts values in ascending order (smallest to largest, A-Z, earliest to latest).'desc': Sorts values in descending order (largest to smallest, Z-A, latest to earliest).
These values are passed as the third argument (orders)
to the _.orderBy method, either as a single string or as an
array of strings corresponding to each sort iteratee.
Default Sorting Direction
If you do not supply the orders argument,
_.orderBy defaults to ascending ('asc') order
for all specified iteratees.
const users = [
{ user: 'fred', age: 48 },
{ user: 'barney', age: 34 },
{ user: 'fred', age: 40 }
];
// Defaults to 'asc' for both iteratees
const sorted = _.orderBy(users, ['user', 'age']);Applying a Single Sorting Direction
To sort a collection by a single property in descending order, supply
'desc' in the orders parameter:
const sortedByAgeDesc = _.orderBy(users, ['age'], ['desc']);
// Result: fred (48), fred (40), barney (34)Applying Multiple Sorting Directions
When sorting by multiple properties, you can supply an array of directions matching the array of iteratees. This allows you to mix ascending and descending sorts within the same operation:
// Sort by 'user' ascending, then by 'age' descending
const sortedMixed = _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
// Result: barney (34), fred (48), fred (40)If the orders array contains fewer elements than the
iteratees array, any iteratee without a specified direction defaults to
'asc'.