0
# Lodash OrderBy
1
2
The lodash method `orderBy` exported as a standalone module for sorting collections by multiple iteratees with configurable sort orders. This utility extends the functionality of `sortBy` by allowing specification of sort direction (ascending or descending) for each criterion.
3
4
## Package Information
5
6
- **Package Name**: lodash.orderby
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.orderby`
10
11
## Core Imports
12
13
```javascript
14
const orderBy = require('lodash.orderby');
15
```
16
17
For ES6 environments:
18
19
```javascript
20
import orderBy from 'lodash.orderby';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const orderBy = require('lodash.orderby');
27
28
const users = [
29
{ 'user': 'fred', 'age': 48 },
30
{ 'user': 'barney', 'age': 34 },
31
{ 'user': 'fred', 'age': 42 },
32
{ 'user': 'barney', 'age': 36 }
33
];
34
35
// Sort by user ascending, then by age descending
36
const result = orderBy(users, ['user', 'age'], ['asc', 'desc']);
37
// => [
38
// { 'user': 'barney', 'age': 36 },
39
// { 'user': 'barney', 'age': 34 },
40
// { 'user': 'fred', 'age': 48 },
41
// { 'user': 'fred', 'age': 42 }
42
// ]
43
44
// Sort by single property with specified order
45
const byUser = orderBy(users, 'user', 'desc');
46
// => sorted by user in descending order
47
48
// Default ascending order when orders not specified
49
const defaultSort = orderBy(users, ['user', 'age']);
50
// => sorted by user ascending, then age ascending
51
```
52
53
## Capabilities
54
55
### Multi-Criteria Sorting
56
57
The `orderBy` function sorts collections by multiple iteratees with configurable sort orders.
58
59
```javascript { .api }
60
/**
61
* Creates an array of elements, sorted in ascending or descending order by the results
62
* of running each element in a collection thru each iteratee. This method performs a
63
* stable sort, that is, it preserves the original sort order of equal elements. The
64
* iteratees are invoked with one argument: (value).
65
*
66
* @param {Array|Object} collection The collection to iterate over.
67
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
68
* The iteratees to sort by.
69
* @param {string[]} [orders] The sort orders of `iteratees`.
70
* @returns {Array} Returns the new sorted array.
71
*/
72
function orderBy(collection, iteratees, orders);
73
```
74
75
**Parameters:**
76
77
- `collection` (Array|Object): The collection to iterate over. Can be an array of objects, array of primitives, or object with enumerable properties.
78
- `[iteratees=[_.identity]]` (Array[]|Function[]|Object[]|string[]): The iteratees to sort by. Can be:
79
- **String**: Property path (e.g., `'user'`, `'user.name'`, `'address.city'`)
80
- **Function**: Custom sorting function that returns a comparable value
81
- **Array**: Multiple criteria combining strings and functions
82
- **Object**: Property descriptor (advanced usage)
83
- `[orders]` (string[]): The sort orders of iteratees. Values can be:
84
- `'asc'`: Ascending order (default if not specified)
85
- `'desc'`: Descending order
86
- Array of orders corresponding to each iteratee
87
88
**Returns:** (Array) Returns a new sorted array. Original collection is not modified.
89
90
**Usage Examples:**
91
92
```javascript
93
const orderBy = require('lodash.orderby');
94
95
// Example data
96
const products = [
97
{ name: 'iPhone', price: 999, category: 'Electronics', rating: 4.5 },
98
{ name: 'MacBook', price: 1299, category: 'Electronics', rating: 4.8 },
99
{ name: 'Desk', price: 299, category: 'Furniture', rating: 4.2 },
100
{ name: 'Chair', price: 199, category: 'Furniture', rating: 4.0 }
101
];
102
103
// Sort by category ascending, then price descending
104
const sorted1 = orderBy(products, ['category', 'price'], ['asc', 'desc']);
105
106
// Sort using custom function
107
const sorted2 = orderBy(products, [
108
'category',
109
(product) => product.rating * product.price
110
], ['asc', 'desc']);
111
112
// Sort by nested property path
113
const users = [
114
{ profile: { name: 'Alice', stats: { score: 95 } } },
115
{ profile: { name: 'Bob', stats: { score: 87 } } }
116
];
117
const sortedUsers = orderBy(users, 'profile.stats.score', 'desc');
118
119
// Sort array of primitives
120
const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
121
const sortedNumbers = orderBy(numbers, null, 'desc');
122
// => [9, 6, 5, 4, 3, 2, 1, 1]
123
124
// Mixed iteratees and orders
125
const mixed = orderBy(products,
126
['category', (p) => p.name.length, 'price'],
127
['asc', 'desc', 'asc']
128
);
129
```
130
131
**Error Handling:**
132
133
- Returns empty array `[]` when `collection` is `null` or `undefined`
134
- Treats missing `iteratees` parameter as identity function (sorts by element value)
135
- Defaults to ascending order when `orders` array is shorter than `iteratees` array
136
- Handles mixed data types consistently with JavaScript's native comparison rules
137
138
**Performance Characteristics:**
139
140
- Uses stable sorting algorithm that preserves relative order of equal elements
141
- Time complexity: O(n log n) where n is the collection length
142
- Space complexity: O(n) for creating the sorted result array
143
- Optimized for multiple sort criteria with efficient comparison functions
144
145
**Type Coercion and Edge Cases:**
146
147
```javascript
148
// Handles null/undefined values gracefully
149
const withNulls = [
150
{ name: 'Alice', score: 95 },
151
{ name: null, score: 87 },
152
{ name: 'Bob', score: null }
153
];
154
const sorted = orderBy(withNulls, ['name', 'score'], ['asc', 'desc']);
155
156
// String objects as orders (less common usage)
157
const stringOrder = orderBy(users, 'name', Object('desc'));
158
159
// Works with object collections (iterates over enumerable properties)
160
const objCollection = {
161
a: { value: 3 },
162
b: { value: 1 },
163
c: { value: 2 }
164
};
165
const sortedObj = orderBy(objCollection, 'value', 'asc');
166
// => [{ value: 1 }, { value: 2 }, { value: 3 }]
167
```