Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var createAggregator = require('../internal/createAggregator');
2
3
/** Used for native method references. */
4
var objectProto = Object.prototype;
5
6
/** Used to check objects for own properties. */
7
var hasOwnProperty = objectProto.hasOwnProperty;
8
9
/**
10
* Creates an object composed of keys generated from the results of running
11
* each element of `collection` through `iteratee`. The corresponding value
12
* of each key is an array of the elements responsible for generating the key.
13
* The `iteratee` is bound to `thisArg` and invoked with three arguments:
14
* (value, index|key, collection).
15
*
16
* If a property name is provided for `iteratee` the created `_.property`
17
* style callback returns the property value of the given element.
18
*
19
* If a value is also provided for `thisArg` the created `_.matchesProperty`
20
* style callback returns `true` for elements that have a matching property
21
* value, else `false`.
22
*
23
* If an object is provided for `iteratee` the created `_.matches` style
24
* callback returns `true` for elements that have the properties of the given
25
* object, else `false`.
26
*
27
* @static
28
* @memberOf _
29
* @category Collection
30
* @param {Array|Object|string} collection The collection to iterate over.
31
* @param {Function|Object|string} [iteratee=_.identity] The function invoked
32
* per iteration.
33
* @param {*} [thisArg] The `this` binding of `iteratee`.
34
* @returns {Object} Returns the composed aggregate object.
35
* @example
36
*
37
* _.groupBy([4.2, 6.1, 6.4], function(n) {
38
* return Math.floor(n);
39
* });
40
* // => { '4': [4.2], '6': [6.1, 6.4] }
41
*
42
* _.groupBy([4.2, 6.1, 6.4], function(n) {
43
* return this.floor(n);
44
* }, Math);
45
* // => { '4': [4.2], '6': [6.1, 6.4] }
46
*
47
* // using the `_.property` callback shorthand
48
* _.groupBy(['one', 'two', 'three'], 'length');
49
* // => { '3': ['one', 'two'], '5': ['three'] }
50
*/
51
var groupBy = createAggregator(function(result, value, key) {
52
if (hasOwnProperty.call(result, key)) {
53
result[key].push(value);
54
} else {
55
result[key] = [value];
56
}
57
});
58
59
module.exports = groupBy;
60
61