You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.6 KiB

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