groupBy.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var createAggregator = require('./_createAggregator');
  2. /** Used for built-in 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` thru `iteratee`. The order of grouped values
  9. * is determined by the order they occur in `collection`. The corresponding
  10. * value of each key is an array of elements responsible for generating the
  11. * key. The iteratee is invoked with one argument: (value).
  12. *
  13. * @static
  14. * @memberOf _
  15. * @since 0.1.0
  16. * @category Collection
  17. * @param {Array|Object} collection The collection to iterate over.
  18. * @param {Array|Function|Object|string} [iteratee=_.identity]
  19. * The iteratee to transform keys.
  20. * @returns {Object} Returns the composed aggregate object.
  21. * @example
  22. *
  23. * _.groupBy([6.1, 4.2, 6.3], Math.floor);
  24. * // => { '4': [4.2], '6': [6.1, 6.3] }
  25. *
  26. * // The `_.property` iteratee shorthand.
  27. * _.groupBy(['one', 'two', 'three'], 'length');
  28. * // => { '3': ['one', 'two'], '5': ['three'] }
  29. */
  30. var groupBy = createAggregator(function(result, value, key) {
  31. if (hasOwnProperty.call(result, key)) {
  32. result[key].push(value);
  33. } else {
  34. result[key] = [value];
  35. }
  36. });
  37. module.exports = groupBy;