0
# lodash.sortby
1
2
The modern build of lodash's `sortBy` function exported as a standalone module. This package provides a stable sorting utility that creates arrays of elements sorted in ascending order by the results of running each element through an iteratee function. It supports various callback styles including property shortcuts, matches callbacks, and matchesProperty callbacks.
3
4
## Package Information
5
6
- **Package Name**: lodash.sortby
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.sortby`
10
- **Dependencies**: This module depends on several internal lodash modules for optimal performance and reusability
11
12
## Core Imports
13
14
```javascript
15
var sortBy = require('lodash.sortby');
16
```
17
18
In modern environments with ES module interop:
19
20
```javascript
21
import sortBy from 'lodash.sortby';
22
```
23
24
## Basic Usage
25
26
```javascript
27
var sortBy = require('lodash.sortby');
28
29
// Sort by function iteratee
30
var users = [
31
{ 'user': 'fred', 'age': 48 },
32
{ 'user': 'barney', 'age': 36 },
33
{ 'user': 'fred', 'age': 40 },
34
{ 'user': 'barney', 'age': 34 }
35
];
36
37
// Sort by age
38
var result = sortBy(users, function(o) { return o.age; });
39
// => [{ 'user': 'barney', 'age': 34 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'fred', 'age': 48 }]
40
41
// Sort by property shorthand
42
var result = sortBy(users, 'age');
43
// => [{ 'user': 'barney', 'age': 34 }, { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'fred', 'age': 48 }]
44
```
45
46
## Capabilities
47
48
### Array Sorting
49
50
Creates an array of elements sorted in ascending order by the results of running each element through an iteratee function. Performs stable sorting that preserves the original order of equal elements.
51
52
```javascript { .api }
53
/**
54
* Creates an array of elements, sorted in ascending order by the results of
55
* running each element in a collection through `iteratee`. This method performs
56
* a stable sort, that is, it preserves the original sort order of equal elements.
57
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
58
* (value, index|key, collection).
59
*
60
* @param {Array|Object|string} collection The collection to iterate over.
61
* @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
62
* @param {*} [thisArg] The `this` binding of `iteratee`.
63
* @returns {Array} Returns the new sorted array.
64
*/
65
function sortBy(collection, iteratee, thisArg);
66
```
67
68
**Parameters:**
69
70
- `collection` (Array|Object|string): The collection to iterate over. If null or undefined, returns empty array.
71
- `iteratee` (Function|Object|string) [optional]: The function invoked per iteration. Defaults to identity function. Supports multiple callback styles:
72
- **Function**: Custom function receiving (value, index|key, collection) arguments
73
- **String**: Property name for property shorthand (e.g., 'age')
74
- **Object**: Matches object for `_.matches` style callback
75
- `thisArg` (*) [optional]: The `this` binding context for the iteratee function
76
77
**Returns:**
78
79
- `Array`: A new sorted array containing all elements from the collection sorted in ascending order by the iteratee results
80
81
**Iteratee Callback Styles:**
82
83
1. **Function Callback**:
84
```javascript
85
sortBy([1, 2, 3], function(n) { return Math.sin(n); });
86
```
87
88
2. **Property Shorthand**:
89
```javascript
90
sortBy(users, 'user'); // sorts by 'user' property
91
```
92
93
3. **Matches Object**:
94
```javascript
95
sortBy(users, { 'active': true }); // sorts by matching { 'active': true }
96
```
97
98
4. **MatchesProperty**:
99
```javascript
100
sortBy(users, 'active', true); // sorts by 'active' property matching true
101
```
102
103
**Key Features:**
104
105
- **Stable Sort**: Preserves original order of equal elements. Elements that compare as equal maintain their relative position from the original collection.
106
- **Null-Safe**: Handles null/undefined collections gracefully, returning empty array
107
- **Type-Flexible**: Works with arrays, objects, and strings as input collections
108
- **Performance-Optimized**: Uses Schwartzian transform (decorate-sort-undecorate) pattern internally
109
110
**Usage Examples:**
111
112
```javascript
113
// Sort numbers by mathematical function
114
sortBy([1, 2, 3], function(n) {
115
return Math.sin(n);
116
});
117
// => [3, 1, 2]
118
119
// Sort with thisArg binding
120
sortBy([1, 2, 3], function(n) {
121
return this.sin(n);
122
}, Math);
123
// => [3, 1, 2]
124
125
// Sort objects by property
126
var users = [
127
{ 'user': 'fred' },
128
{ 'user': 'pebbles' },
129
{ 'user': 'barney' }
130
];
131
132
// Using property shorthand
133
sortBy(users, 'user');
134
// => [{ 'user': 'barney' }, { 'user': 'fred' }, { 'user': 'pebbles' }]
135
136
// Demonstrating stable sort behavior with equal elements
137
var items = [
138
{ name: 'apple', score: 5, id: 1 },
139
{ name: 'banana', score: 3, id: 2 },
140
{ name: 'cherry', score: 5, id: 3 },
141
{ name: 'date', score: 3, id: 4 }
142
];
143
144
// Equal scores maintain original order (stable sort)
145
sortBy(items, 'score');
146
// => [{ name: 'banana', score: 3, id: 2 }, { name: 'date', score: 3, id: 4 },
147
// { name: 'apple', score: 5, id: 1 }, { name: 'cherry', score: 5, id: 3 }]
148
149
// Using property shorthand with lodash pluck pattern
150
var users = [
151
{ 'user': 'fred' },
152
{ 'user': 'pebbles' },
153
{ 'user': 'barney' }
154
];
155
156
// Extract sorted property values (requires additional lodash.pluck or map)
157
var sortedUsers = sortBy(users, 'user');
158
// => [{ 'user': 'barney' }, { 'user': 'fred' }, { 'user': 'pebbles' }]
159
160
// Empty/null collections
161
sortBy(null); // => []
162
sortBy(undefined); // => []
163
sortBy([]); // => []
164
```