sortByAll.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var baseFlatten = require('../internal/baseFlatten'),
  2. baseSortByOrder = require('../internal/baseSortByOrder'),
  3. isIterateeCall = require('../internal/isIterateeCall'),
  4. restParam = require('../function/restParam');
  5. /**
  6. * This method is like `_.sortBy` except that it can sort by multiple iteratees
  7. * or property names.
  8. *
  9. * If a property name is provided for an iteratee the created `_.property`
  10. * style callback returns the property value of the given element.
  11. *
  12. * If an object is provided for an iteratee the created `_.matches` style
  13. * callback returns `true` for elements that have the properties of the given
  14. * object, else `false`.
  15. *
  16. * @static
  17. * @memberOf _
  18. * @category Collection
  19. * @param {Array|Object|string} collection The collection to iterate over.
  20. * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
  21. * The iteratees to sort by, specified as individual values or arrays of values.
  22. * @returns {Array} Returns the new sorted array.
  23. * @example
  24. *
  25. * var users = [
  26. * { 'user': 'fred', 'age': 48 },
  27. * { 'user': 'barney', 'age': 36 },
  28. * { 'user': 'fred', 'age': 42 },
  29. * { 'user': 'barney', 'age': 34 }
  30. * ];
  31. *
  32. * _.map(_.sortByAll(users, ['user', 'age']), _.values);
  33. * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
  34. *
  35. * _.map(_.sortByAll(users, 'user', function(chr) {
  36. * return Math.floor(chr.age / 10);
  37. * }), _.values);
  38. * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
  39. */
  40. var sortByAll = restParam(function(collection, iteratees) {
  41. if (collection == null) {
  42. return [];
  43. }
  44. var guard = iteratees[2];
  45. if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
  46. iteratees.length = 1;
  47. }
  48. return baseSortByOrder(collection, baseFlatten(iteratees), []);
  49. });
  50. module.exports = sortByAll;