Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseSortByOrder = require('../internal/baseSortByOrder'),
2
isArray = require('../lang/isArray'),
3
isIterateeCall = require('../internal/isIterateeCall');
4
5
/**
6
* This method is like `_.sortByAll` except that it allows specifying the
7
* sort orders of the iteratees to sort by. A truthy value in `orders` will
8
* sort the corresponding property name in ascending order while a falsey
9
* value will sort it in descending order.
10
*
11
* If a property name is provided for an iteratee the created `_.property`
12
* style callback returns the property value of the given element.
13
*
14
* If an object is provided for an iteratee the created `_.matches` style
15
* callback returns `true` for elements that have the properties of the given
16
* object, else `false`.
17
*
18
* @static
19
* @memberOf _
20
* @category Collection
21
* @param {Array|Object|string} collection The collection to iterate over.
22
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
23
* @param {boolean[]} orders The sort orders of `iteratees`.
24
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
25
* @returns {Array} Returns the new sorted array.
26
* @example
27
*
28
* var 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` in ascending order and by `age` in descending order
36
* _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values);
37
* // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
38
*/
39
function sortByOrder(collection, iteratees, orders, guard) {
40
if (collection == null) {
41
return [];
42
}
43
if (guard && isIterateeCall(iteratees, orders, guard)) {
44
orders = null;
45
}
46
if (!isArray(iteratees)) {
47
iteratees = iteratees == null ? [] : [iteratees];
48
}
49
if (!isArray(orders)) {
50
orders = orders == null ? [] : [orders];
51
}
52
return baseSortByOrder(collection, iteratees, orders);
53
}
54
55
module.exports = sortByOrder;
56
57