Skip to the solution
EasyDSAAsked in 20246 min read

Invert Object Keys

384 views

The problem

Problem, as an interviewer would state it: "Implement invert(obj) — swapping every key and value in a plain object, so that a value becomes a key and its original key becomes the new value, matching lodash's own well-known _.invert behavior."

Examples:

Code
invert({a: "x", b: "y", c: "z"}); // {x: "a", y: "b", z: "c"}

Clarifying questions expected:

  • If two different keys share the SAME value, which of the two original keys should genuinely win in the inverted result?
  • Should the original object remain completely untouched, with a genuinely NEW object returned?
  • What should happen to a value that is not naturally string-like, like a number — does it need to be coerced?

Code / implementation expected: Yes — real, direct proof of a basic key/value swap, a duplicate-value collision case, and confirmation the original object is never mutated.

  • object

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: invert() correctly swaps keys and values, with a duplicate-value collision correctly keeping the last key, and no mutation of the original

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 38 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement Your Own Array.prototype.reduceRight()

Continue