forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
countBy.js
41 lines (38 loc) · 1.22 KB
/
countBy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import baseAssignValue from './.internal/baseAssignValue.js'
import reduce from './reduce.js'
/** Used to check objects for own properties. */
const hasOwnProperty = Object.prototype.hasOwnProperty
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* const users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'betty', 'active': true },
* { 'user': 'fred', 'active': false }
* ]
*
* countBy(users, 'active');
* // => { 'true': 2, 'false': 1 }
*/
function countBy(collection, iteratee) {
return reduce(collection, (result, value, key) => {
key = iteratee(value)
if (hasOwnProperty.call(result, key)) {
++result[key]
} else {
baseAssignValue(result, key, 1)
}
return result
}, {})
}
export default countBy