forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
invertBy.js
36 lines (34 loc) · 1.09 KB
/
invertBy.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
/** Used to check objects for own properties. */
const hasOwnProperty = Object.prototype.hasOwnProperty
/**
* This method is like `invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} iteratee The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* const object = { 'a': 1, 'b': 2, 'c': 1 }
*
* invertBy(object, value => `group${value}`)
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
function invertBy(object, iteratee) {
const result = {}
Object.keys(object).forEach((value, key) => {
value = iteratee(value)
if (hasOwnProperty.call(result, value)) {
result[value].push(key)
} else {
result[value] = [key]
}
})
return result
}
export default invertBy