Update invertKeyValues

This commit is contained in:
Angelos Chalaris
2018-01-23 17:31:50 +02:00
parent f264072af0
commit fefea87775
2 changed files with 10 additions and 6 deletions

View File

@ -1,17 +1,21 @@
### invertKeyValues ### invertKeyValues
Inverts the key-value pairs of an object, without mutating it. Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object. Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).
Omit the second argument, `fn`, to get the inverted keys without applying a function to them.
```js ```js
const invertKeyValues = obj => const invertKeyValues = (obj, fn) =>
Object.keys(obj).reduce((acc, key) => { Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key; const val = fn ? fn(obj[key]) : obj[key];
acc[val] = acc[val] || [];
acc[val].push(key);
return acc; return acc;
}, {}); }, {});
``` ```
```js ```js
invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' } invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }
``` ```

View File

@ -85,7 +85,7 @@ initializeArrayWithRangeRight:array,math
initializeArrayWithValues:array,math initializeArrayWithValues:array,math
inRange:math inRange:math
intersection:array,math intersection:array,math
invertKeyValues:object invertKeyValues:object,function
is:type,array,regexp is:type,array,regexp
isAbsoluteURL:string,utility,browser,url isAbsoluteURL:string,utility,browser,url
isArrayLike:type,array isArrayLike:type,array