Introduction
In this lab, we will explore how to invert an object's key-value pairs without mutating the original object. We will use the Object.keys() method and Array.prototype.reduce() to invert the object. Additionally, we will learn how to apply a function to the inverted keys and return an array of keys responsible for generating the inverted value.
Function to Invert an Object
To invert the key-value pairs of an object without altering the original object, use the invertKeyValues function.
Call the function by typing
invertKeyValues(obj, fn)in the Terminal/SSH, whereobjis the object to be inverted andfnis an optional function to be applied to the inverted key.The
Object.keys()andArray.prototype.reduce()methods are used to create a new object with inverted key-value pairs, and if a function is provided, it is applied to each inverted key.If
fnis omitted, the function returns only the inverted keys without any function applied to them.The function returns an object with each inverted value being an array of keys responsible for generating the inverted value.
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;
}, {});
Example usage:
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' ] }
Summary
Congratulations! You have completed the Invert Object lab. You can practice more labs in LabEx to improve your skills.