1 | import baseFlatten from './_baseFlatten';
|
2 | import baseOrderBy from './_baseOrderBy';
|
3 | import isIterateeCall from './_isIterateeCall';
|
4 | import rest from './rest';
|
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 {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
|
18 | * [iteratees=[_.identity]] The iteratees to sort by, specified individually
|
19 | * or in arrays.
|
20 | * @returns {Array} Returns the new sorted array.
|
21 | * @example
|
22 | *
|
23 | * var users = [
|
24 | * { 'user': 'fred', 'age': 48 },
|
25 | * { 'user': 'barney', 'age': 36 },
|
26 | * { 'user': 'fred', 'age': 40 },
|
27 | * { 'user': 'barney', 'age': 34 }
|
28 | * ];
|
29 | *
|
30 | * _.sortBy(users, function(o) { return o.user; });
|
31 | * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
|
32 | *
|
33 | * _.sortBy(users, ['user', 'age']);
|
34 | * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
|
35 | *
|
36 | * _.sortBy(users, 'user', function(o) {
|
37 | * return Math.floor(o.age / 10);
|
38 | * });
|
39 | * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
|
40 | */
|
41 | var sortBy = rest(function(collection, iteratees) {
|
42 | if (collection == null) {
|
43 | return [];
|
44 | }
|
45 | var length = iteratees.length;
|
46 | if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
|
47 | iteratees = [];
|
48 | } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
|
49 | iteratees.length = 1;
|
50 | }
|
51 | return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
|
52 | });
|
53 |
|
54 | export default sortBy;
|