Nest all content into snippets
This commit is contained in:
30
snippets/js/s/invert-key-values.md
Normal file
30
snippets/js/s/invert-key-values.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Invert object
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [object]
|
||||
cover: pineapple-on-green
|
||||
dateModified: 2020-10-20T23:02:01+03:00
|
||||
---
|
||||
|
||||
Inverts the key-value pairs of an object, without mutating it.
|
||||
|
||||
- Use `Object.keys()` and `Array.prototype.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.
|
||||
- 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.
|
||||
|
||||
```js
|
||||
const invertKeyValues = (obj, fn) =>
|
||||
Object.keys(obj).reduce((acc, key) => {
|
||||
const val = fn ? fn(obj[key]) : obj[key];
|
||||
acc[val] = acc[val] || [];
|
||||
acc[val].push(key);
|
||||
return acc;
|
||||
}, {});
|
||||
```
|
||||
|
||||
```js
|
||||
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' ] }
|
||||
```
|
||||
Reference in New Issue
Block a user