Start learning free

LESSON 213 OF 501 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in JavaScript

Practice

Given a dictionary d whose keys and values are strings, return a new dictionary with the keys and values swapped: every value of d becomes a key, and it maps to the key it belonged to.

The order of the entries in the dictionary you return doesn't matter.

Example 1:

Input: d = {"apple": "red", "banana": "yellow", "plum": "purple"}
Output: {"red": "apple", "yellow": "banana", "purple": "plum"}
Explanation: "apple" mapped to "red", so now "red" maps to "apple". The other two entries turn around the same way.

Example 2:

Input: d = {"cat": "dog"}
Output: {"dog": "cat"}
Explanation: One entry gives one entry, turned around.

Example 3:

Input: d = {"a": "b", "b": "c"}
Output: {"b": "a", "c": "b"}
Explanation: "b" is both a key and a value of d. As the value of "a", it becomes a key that maps to "a". As a key, its entry "b": "c" turns into "c": "b".

Rules:

  • d has at least one entry.
  • All the values of d are different, so the result has as many entries as d.
  • Keys and values are words without spaces.
STEP 1 OF 4
    Ctrl + Enter to check

    Invert A Dictionary in JavaScript

    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free