1 var baseCallback = require('../internal/baseCallback'),
2 baseMap = require('../internal/baseMap'),
3 baseSortBy = require('../internal/baseSortBy'),
4 compareAscending = require('../internal/compareAscending'),
5 isIterateeCall = require('../internal/isIterateeCall');
8 * Creates an array of elements, sorted in ascending order by the results of
9 * running each element in a collection through `iteratee`. This method performs
10 * a stable sort, that is, it preserves the original sort order of equal elements.
11 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
12 * (value, index|key, collection).
14 * If a property name is provided for `iteratee` the created `_.property`
15 * style callback returns the property value of the given element.
17 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18 * style callback returns `true` for elements that have a matching property
19 * value, else `false`.
21 * If an object is provided for `iteratee` the created `_.matches` style
22 * callback returns `true` for elements that have the properties of the given
23 * object, else `false`.
27 * @category Collection
28 * @param {Array|Object|string} collection The collection to iterate over.
29 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
31 * @param {*} [thisArg] The `this` binding of `iteratee`.
32 * @returns {Array} Returns the new sorted array.
35 * _.sortBy([1, 2, 3], function(n) {
40 * _.sortBy([1, 2, 3], function(n) {
47 * { 'user': 'pebbles' },
48 * { 'user': 'barney' }
51 * // using the `_.property` callback shorthand
52 * _.pluck(_.sortBy(users, 'user'), 'user');
53 * // => ['barney', 'fred', 'pebbles']
55 function sortBy(collection, iteratee, thisArg) {
56 if (collection == null) {
59 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
63 iteratee = baseCallback(iteratee, thisArg, 3);
65 var result = baseMap(collection, function(value, key, collection) {
66 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
68 return baseSortBy(result, compareAscending);
71 module.exports = sortBy;