mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-29 06:27:49 +00:00
56 lines
2.1 KiB
JavaScript
56 lines
2.1 KiB
JavaScript
define(['./_baseFlatten', './_baseOrderBy', './isArray', './_isFlattenableIteratee', './_isIterateeCall', './rest'], function(baseFlatten, baseOrderBy, isArray, isFlattenableIteratee, isIterateeCall, rest) {
|
|
|
|
/**
|
|
* Creates an array of elements, sorted in ascending order by the results of
|
|
* running each element in a collection thru each iteratee. This method
|
|
* performs a stable sort, that is, it preserves the original sort order of
|
|
* equal elements. The iteratees are invoked with one argument: (value).
|
|
*
|
|
* @static
|
|
* @memberOf _
|
|
* @since 0.1.0
|
|
* @category Collection
|
|
* @param {Array|Object} collection The collection to iterate over.
|
|
* @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
|
|
* [iteratees=[_.identity]] The iteratees to sort by.
|
|
* @returns {Array} Returns the new sorted array.
|
|
* @example
|
|
*
|
|
* var users = [
|
|
* { 'user': 'fred', 'age': 48 },
|
|
* { 'user': 'barney', 'age': 36 },
|
|
* { 'user': 'fred', 'age': 40 },
|
|
* { 'user': 'barney', 'age': 34 }
|
|
* ];
|
|
*
|
|
* _.sortBy(users, function(o) { return o.user; });
|
|
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
|
|
*
|
|
* _.sortBy(users, ['user', 'age']);
|
|
* // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
|
|
*
|
|
* _.sortBy(users, 'user', function(o) {
|
|
* return Math.floor(o.age / 10);
|
|
* });
|
|
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
|
|
*/
|
|
var sortBy = rest(function(collection, iteratees) {
|
|
if (collection == null) {
|
|
return [];
|
|
}
|
|
var length = iteratees.length;
|
|
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
|
|
iteratees = [];
|
|
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
|
|
iteratees = [iteratees[0]];
|
|
}
|
|
iteratees = (iteratees.length == 1 && isArray(iteratees[0]))
|
|
? iteratees[0]
|
|
: baseFlatten(iteratees, 1, isFlattenableIteratee);
|
|
|
|
return baseOrderBy(collection, iteratees, []);
|
|
});
|
|
|
|
return sortBy;
|
|
});
|