Start learning free

LESSON 230 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in TypeScript: Pairing by Index

Practice Read the full explanation

Given an array of strings names and an array of integers scores of the same length, pair each name with the score at the same index. Return a dictionary where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty dictionary. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in TypeScript, explained

    Problem overview

    The method toDictionary receives an array of strings, names, and an array of numbers, scores, of the same length. It returns an object where each names[i] is a key and scores[i] is its value. The names are all different, two names can share a score, and two empty arrays give an empty object.

    For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the result is {"Ana": 90, "Ben": 75, "Cara": 88}. "Ana" is at index 0 and so is 90, and the same holds for the other two. With ["Zoe", "Adam"] and [60, 60], the result is {"Zoe": 60, "Adam": 60}: equal scores are no problem, because only keys must be unique.

    Approach

    A name and its score sit at the same position in their arrays, so one index reaches both. Loop over the positions, and at each one store the pair in the object. Assigning to a key that isn't there yet adds it, so there is no need to check anything first.

    That makes the loop body a single line, with no counting and no branches. It is a good first example of building an object from data: start empty, add one entry per round, return the object.

    On the first example the loop runs three times. At i = 0 the object gets "Ana": 90, at i = 1 it gets "Ben": 75, and at i = 2 it gets "Cara": 88. The object grows by one entry per round, and the arrays are never changed.

    Step by step

    1. Create the empty object. result is declared with const and the type { [key: string]: number }: string keys, number values.
    2. Loop over the indexes. A for loop with let i = 0 that continues while i < names.length and steps up with i++. A plain index loop is needed here, because a for...of loop over names alone wouldn't give you the matching score.
    3. Store the pair. result[names[i]] = scores[i] uses the name as the key and the score as the value.
    4. Return result after the loop.

    The solution in TypeScript

    class Solution {
        toDictionary(names: string[], scores: number[]): { [key: string]: number } {
            const result: { [key: string]: number } = {};
            for (let i = 0; i < names.length; i++) {
                result[names[i]] = scores[i];
            }
            return result;
        }
    }
    

    Details worth knowing:

    • Bracket notation with a variable. result[names[i]] evaluates names[i] first and uses that string as the key. Dot notation, result.name, would always use the key "name" instead.
    • const and the object. const means result always refers to the same object. You can still add keys to it.
    • The loop bound. It uses names.length. Since both arrays have the same length, scores.length would do the same.
    • Types are erased. The index-signature type is only a promise to the compiler. At run time result is a plain object.

    Edge cases and common mistakes

    • Empty arrays. The loop never runs, and the method returns {}.
    • Repeated names. The lesson promises all names differ. If one repeated, the later score would overwrite the earlier: ["Ana", "Ana"] with [1, 2] gives {"Ana": 2}.
    • Mixing up key and value. result[scores[i]] = names[i] would build the opposite dictionary.
    • Using <= in the loop. At i = names.length, names[i] is undefined, and the object would get a key named "undefined".

    Testing

    • ["Ana", "Ben", "Cara"] with [90, 75, 88] gives {"Ana":90,"Ben":75,"Cara":88}.
    • ["Zoe", "Adam"] with [60, 60] gives {"Zoe":60,"Adam":60}.
    • ["Max"] with [100] gives {"Max":100}.
    • [] with [] gives {}.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free