Start learning free

LESSON 228 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in JavaScript: Swap Keys and Values

Practice Read the full explanation

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

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in JavaScript, explained

    Problem overview

    The method invertDictionary(d) receives an object whose keys and values are strings and returns a new object with the roles swapped: each value of d becomes a key, and it maps to the key it came from.

    For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {"red": "apple", "yellow": "banana", "purple": "plum"}. The input {"a": "b", "b": "c"} gives {"b": "a", "c": "b"}. The word "b" is a key in the input and a value too, and the swap handles each role separately.

    Approach

    Read every entry of d as a pair and write it into a new object reversed. Because the lesson guarantees that all values are different, no two entries land on the same new key, so nothing is overwritten and the result has as many entries as d.

    The result must be a new object, not a change to d. Modifying an object while looping over it makes it easy to lose or revisit entries, and the caller usually expects the original to stay as it was.

    Step by step

    1. Create an empty object named result with const.
    2. Loop over the entries with for (const [key, value] of Object.entries(d)). Object.entries(d) returns an array of [key, value] pairs, and the square brackets in the loop header unpack each pair into two variables.
    3. Store the swapped pair: result[value] = key.
    4. Return result after the loop.

    The solution in JavaScript

    class Solution {
        invertDictionary(d) {
            const result = {};
            for (const [key, value] of Object.entries(d)) {
                result[value] = key;
            }
            return result;
        }
    }
    

    The new JavaScript idea here is Object.entries. For {apple: "red", plum: "purple"} it returns [["apple", "red"], ["plum", "purple"]]: an array of two-item arrays. The pattern const [key, value] is destructuring, which takes the first item of each pair as key and the second as value. The variables are const because each pass of the loop creates fresh ones, and they are never reassigned inside it.

    Writing result[value] = key uses square brackets because the key comes from a variable. A loop with for...in would also work, but it visits keys only, and Object.entries gives key and value together.

    Tracing the examples

    For {a: "b", b: "c"}, the entries are ["a", "b"] and ["b", "c"]. The first pass sets result["b"] = "a". The second sets result["c"] = "b". The final object is {b: "a", c: "b"}. The first pass never touches the second entry's key, because d and result are separate objects.

    A shorter form

    The loop has an equivalent in Object.fromEntries: map each pair to its reverse and build an object from the results, as in Object.fromEntries(Object.entries(d).map(([k, v]) => [v, k])). For {apple: "red", banana: "yellow"} it gives {red: "apple", yellow: "banana"}, the same as the loop. Write the loop first: it shows exactly where the swap happens.

    Edge cases and common mistakes

    • Repeated values. The lesson promises none. If two keys shared a value, they would write to the same new key and the later one would win: {a: "x", b: "x"} gives {x: "b"}, so an entry disappears.
    • Writing into d itself. Setting d[value] = key would mix new keys into the original and give the wrong result.
    • Dot notation. result.value = key sets a key literally named "value". Use result[value].
    • One entry. {cat: "dog"} gives {dog: "cat"}.
    • Values must be usable as keys. The lesson uses strings, so they are. Object keys are always strings, so any other value type is converted to text first.

    Testing

    • {apple: "red", banana: "yellow", plum: "purple"} gives {red: "apple", yellow: "banana", purple: "plum"}.
    • {cat: "dog"} gives {dog: "cat"}.
    • {a: "b", b: "c"} gives {b: "a", c: "b"}.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free