Exercise 12: Invert Object (key-value swap)

Problem Statement

Function `invert(obj)` banao jo object ke keys aur values ko swap kare. Example: invert({a: 1, b: 2}) => {1: "a", 2: "b"}

Sample Output:

invert({a: 1, b: 2}) => {1: "a", 2: "b"}
invert({x: "hello"}) => {hello: "x"}

Solution

const invert = (obj) => {
  return Object.keys(obj).reduce((acc, key) => {
    acc[obj[key]] = key;
    return acc;
  }, {});
};

Explanation

Overall Goal:

  • Object ke keys aur values ko swap karna.

Real world:

  • Lookup tables: reverse mapping.
  • Data transformation: value-to-key mapping.