1 | import baseFlatten from './_baseFlatten.js';
|
---|
2 | import baseOrderBy from './_baseOrderBy.js';
|
---|
3 | import baseRest from './_baseRest.js';
|
---|
4 | import isIterateeCall from './_isIterateeCall.js';
|
---|
5 |
|
---|
6 | /**
|
---|
7 | * Creates an array of elements, sorted in ascending order by the results of
|
---|
8 | * running each element in a collection thru each iteratee. This method
|
---|
9 | * performs a stable sort, that is, it preserves the original sort order of
|
---|
10 | * equal elements. The iteratees are invoked with one argument: (value).
|
---|
11 | *
|
---|
12 | * @static
|
---|
13 | * @memberOf _
|
---|
14 | * @since 0.1.0
|
---|
15 | * @category Collection
|
---|
16 | * @param {Array|Object} collection The collection to iterate over.
|
---|
17 | * @param {...(Function|Function[])} [iteratees=[_.identity]]
|
---|
18 | * The iteratees to sort by.
|
---|
19 | * @returns {Array} Returns the new sorted array.
|
---|
20 | * @example
|
---|
21 | *
|
---|
22 | * var users = [
|
---|
23 | * { 'user': 'fred', 'age': 48 },
|
---|
24 | * { 'user': 'barney', 'age': 36 },
|
---|
25 | * { 'user': 'fred', 'age': 30 },
|
---|
26 | * { 'user': 'barney', 'age': 34 }
|
---|
27 | * ];
|
---|
28 | *
|
---|
29 | * _.sortBy(users, [function(o) { return o.user; }]);
|
---|
30 | * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
|
---|
31 | *
|
---|
32 | * _.sortBy(users, ['user', 'age']);
|
---|
33 | * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
|
---|
34 | */
|
---|
35 | var sortBy = baseRest(function(collection, iteratees) {
|
---|
36 | if (collection == null) {
|
---|
37 | return [];
|
---|
38 | }
|
---|
39 | var length = iteratees.length;
|
---|
40 | if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
|
---|
41 | iteratees = [];
|
---|
42 | } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
|
---|
43 | iteratees = [iteratees[0]];
|
---|
44 | }
|
---|
45 | return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
|
---|
46 | });
|
---|
47 |
|
---|
48 | export default sortBy;
|
---|