JavaScript: Invert the key-value pairs of an object, without mutating it
JavaScript fundamental (ES6 Syntax): Exercise-78 with Solution
Write a JavaScript program to invert 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.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.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
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;
}, {});
console.log(invertKeyValues({ a: 1, b: 2, c: 1 }));
console.log(invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value));
Sample Output:
{"1":["a","c"],"2":["b"]} {"group1":["a","c"],"group2":["b"]}
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-78-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to iterate over all own properties of an object, running a callback for each one.
Next: Write a JavaScript program to take any number of iterable objects or objects with a length property and returns the longest one.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join