sortByOrder.js 2.0 KB

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