選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

groupBy.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var baseAssignValue = require('./_baseAssignValue'),
  2. createAggregator = require('./_createAggregator');
  3. /** Used for built-in method references. */
  4. var objectProto = Object.prototype;
  5. /** Used to check objects for own properties. */
  6. var hasOwnProperty = objectProto.hasOwnProperty;
  7. /**
  8. * Creates an object composed of keys generated from the results of running
  9. * each element of `collection` thru `iteratee`. The order of grouped values
  10. * is determined by the order they occur in `collection`. The corresponding
  11. * value of each key is an array of elements responsible for generating the
  12. * key. The iteratee is invoked with one argument: (value).
  13. *
  14. * @static
  15. * @memberOf _
  16. * @since 0.1.0
  17. * @category Collection
  18. * @param {Array|Object} collection The collection to iterate over.
  19. * @param {Function} [iteratee=_.identity] 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. baseAssignValue(result, key, [value]);
  35. }
  36. });
  37. module.exports = groupBy;