sortBy.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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');
  6. /**
  7. * Creates an array of elements, sorted in ascending order by the results of
  8. * running each element in a collection through `iteratee`. This method performs
  9. * a stable sort, that is, it preserves the original sort order of equal elements.
  10. * The `iteratee` is bound to `thisArg` and invoked with three arguments:
  11. * (value, index|key, collection).
  12. *
  13. * If a property name is provided for `iteratee` the created `_.property`
  14. * style callback returns the property value of the given element.
  15. *
  16. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  17. * style callback returns `true` for elements that have a matching property
  18. * value, else `false`.
  19. *
  20. * If an object is provided for `iteratee` the created `_.matches` style
  21. * callback returns `true` for elements that have the properties of the given
  22. * object, else `false`.
  23. *
  24. * @static
  25. * @memberOf _
  26. * @category Collection
  27. * @param {Array|Object|string} collection The collection to iterate over.
  28. * @param {Function|Object|string} [iteratee=_.identity] The function invoked
  29. * per iteration.
  30. * @param {*} [thisArg] The `this` binding of `iteratee`.
  31. * @returns {Array} Returns the new sorted array.
  32. * @example
  33. *
  34. * _.sortBy([1, 2, 3], function(n) {
  35. * return Math.sin(n);
  36. * });
  37. * // => [3, 1, 2]
  38. *
  39. * _.sortBy([1, 2, 3], function(n) {
  40. * return this.sin(n);
  41. * }, Math);
  42. * // => [3, 1, 2]
  43. *
  44. * var users = [
  45. * { 'user': 'fred' },
  46. * { 'user': 'pebbles' },
  47. * { 'user': 'barney' }
  48. * ];
  49. *
  50. * // using the `_.property` callback shorthand
  51. * _.pluck(_.sortBy(users, 'user'), 'user');
  52. * // => ['barney', 'fred', 'pebbles']
  53. */
  54. function sortBy(collection, iteratee, thisArg) {
  55. if (collection == null) {
  56. return [];
  57. }
  58. if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
  59. iteratee = undefined;
  60. }
  61. var index = -1;
  62. iteratee = baseCallback(iteratee, thisArg, 3);
  63. var result = baseMap(collection, function(value, key, collection) {
  64. return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
  65. });
  66. return baseSortBy(result, compareAscending);
  67. }
  68. module.exports = sortBy;