groupBy.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var createAggregator = require('../internal/createAggregator');
  2. /** Used for native method references. */
  3. var objectProto = Object.prototype;
  4. /** Used to check objects for own properties. */
  5. var hasOwnProperty = objectProto.hasOwnProperty;
  6. /**
  7. * Creates an object composed of keys generated from the results of running
  8. * each element of `collection` through `iteratee`. The corresponding value
  9. * of each key is an array of the elements responsible for generating the key.
  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 {Object} Returns the composed aggregate object.
  32. * @example
  33. *
  34. * _.groupBy([4.2, 6.1, 6.4], function(n) {
  35. * return Math.floor(n);
  36. * });
  37. * // => { '4': [4.2], '6': [6.1, 6.4] }
  38. *
  39. * _.groupBy([4.2, 6.1, 6.4], function(n) {
  40. * return this.floor(n);
  41. * }, Math);
  42. * // => { '4': [4.2], '6': [6.1, 6.4] }
  43. *
  44. * // using the `_.property` callback shorthand
  45. * _.groupBy(['one', 'two', 'three'], 'length');
  46. * // => { '3': ['one', 'two'], '5': ['three'] }
  47. */
  48. var groupBy = createAggregator(function(result, value, key) {
  49. if (hasOwnProperty.call(result, key)) {
  50. result[key].push(value);
  51. } else {
  52. result[key] = [value];
  53. }
  54. });
  55. module.exports = groupBy;