UNPKG

1.35 kBJavaScriptView Raw
1import createAggregator from './_createAggregator';
2
3/** Used for built-in method references. */
4var objectProto = Object.prototype;
5
6/** Used to check objects for own properties. */
7var hasOwnProperty = objectProto.hasOwnProperty;
8
9/**
10 * Creates an object composed of keys generated from the results of running
11 * each element of `collection` thru `iteratee`. The order of grouped values
12 * is determined by the order they occur in `collection`. The corresponding
13 * value of each key is an array of elements responsible for generating the
14 * key. The iteratee is invoked with one argument: (value).
15 *
16 * @static
17 * @memberOf _
18 * @since 0.1.0
19 * @category Collection
20 * @param {Array|Object} collection The collection to iterate over.
21 * @param {Array|Function|Object|string} [iteratee=_.identity]
22 * The iteratee to transform keys.
23 * @returns {Object} Returns the composed aggregate object.
24 * @example
25 *
26 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
27 * // => { '4': [4.2], '6': [6.1, 6.3] }
28 *
29 * // The `_.property` iteratee shorthand.
30 * _.groupBy(['one', 'two', 'three'], 'length');
31 * // => { '3': ['one', 'two'], '5': ['three'] }
32 */
33var groupBy = createAggregator(function(result, value, key) {
34 if (hasOwnProperty.call(result, key)) {
35 result[key].push(value);
36 } else {
37 result[key] = [value];
38 }
39});
40
41export default groupBy;