From 61120916ded880446fa3bf9f59ae706bc0d5825e Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 1 Jan 2018 17:33:46 +0200 Subject: [PATCH] Add invertKeyValues Inverts the key-value pairs of an object --- snippets/invertKeyValues.md | 13 +++++++++++++ tag_database | 1 + 2 files changed, 14 insertions(+) create mode 100644 snippets/invertKeyValues.md diff --git a/snippets/invertKeyValues.md b/snippets/invertKeyValues.md new file mode 100644 index 000000000..b3a7ce11d --- /dev/null +++ b/snippets/invertKeyValues.md @@ -0,0 +1,13 @@ +### invertKeyValues + +Inverts the key-value pairs of an object, without mutating it. + +Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object. + +```js +const invertKeyValues = obj => Object.keys(obj).reduce((acc,key) => { acc[obj[key]] = key; return acc;},{}); +``` + +```js +invertKeyValues({name:'John', age: 20}) // { 20: 'age', John: 'name' } +``` diff --git a/tag_database b/tag_database index 185d2ee1f..64503984d 100644 --- a/tag_database +++ b/tag_database @@ -65,6 +65,7 @@ initializeArrayWithRange:array initializeArrayWithValues:array inRange:math intersection:array +invertKeyValues:object isAbsoluteURL:string isArmstrongNumber:math isArray:utility