orderBy.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var baseOrderBy = require('./_baseOrderBy'),
  2. isArray = require('./isArray');
  3. /**
  4. * This method is like `_.sortBy` except that it allows specifying the sort
  5. * orders of the iteratees to sort by. If `orders` is unspecified, all values
  6. * are sorted in ascending order. Otherwise, specify an order of "desc" for
  7. * descending or "asc" for ascending sort order of corresponding values.
  8. *
  9. * @static
  10. * @memberOf _
  11. * @since 4.0.0
  12. * @category Collection
  13. * @param {Array|Object} collection The collection to iterate over.
  14. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
  15. * The iteratees to sort by.
  16. * @param {string[]} [orders] The sort orders of `iteratees`.
  17. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
  18. * @returns {Array} Returns the new sorted array.
  19. * @example
  20. *
  21. * var users = [
  22. * { 'user': 'fred', 'age': 48 },
  23. * { 'user': 'barney', 'age': 34 },
  24. * { 'user': 'fred', 'age': 40 },
  25. * { 'user': 'barney', 'age': 36 }
  26. * ];
  27. *
  28. * // Sort by `user` in ascending order and by `age` in descending order.
  29. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
  30. * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
  31. */
  32. function orderBy(collection, iteratees, orders, guard) {
  33. if (collection == null) {
  34. return [];
  35. }
  36. if (!isArray(iteratees)) {
  37. iteratees = iteratees == null ? [] : [iteratees];
  38. }
  39. orders = guard ? undefined : orders;
  40. if (!isArray(orders)) {
  41. orders = orders == null ? [] : [orders];
  42. }
  43. return baseOrderBy(collection, iteratees, orders);
  44. }
  45. module.exports = orderBy;