countBy.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  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 corresponding value of
  9. * each key is the number of times the key was returned by `iteratee`. The
  10. * iteratee is invoked with one argument: (value).
  11. *
  12. * @static
  13. * @memberOf _
  14. * @since 0.5.0
  15. * @category Collection
  16. * @param {Array|Object} collection The collection to iterate over.
  17. * @param {Array|Function|Object|string} [iteratee=_.identity]
  18. * The iteratee to transform keys.
  19. * @returns {Object} Returns the composed aggregate object.
  20. * @example
  21. *
  22. * _.countBy([6.1, 4.2, 6.3], Math.floor);
  23. * // => { '4': 1, '6': 2 }
  24. *
  25. * // The `_.property` iteratee shorthand.
  26. * _.countBy(['one', 'two', 'three'], 'length');
  27. * // => { '3': 2, '5': 1 }
  28. */
  29. var countBy = createAggregator(function(result, value, key) {
  30. hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
  31. });
  32. module.exports = countBy;