Start learning free

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

Two Arrays to a Dictionary in JavaScript: Pair Names with Scores

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

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in JavaScript, explained

    Problem overview

    The method toDictionary(names, scores) receives two arrays of the same length: names and scores. It returns an object where each name is a key and the score at the same index is its value.

    For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the result is {"Ana": 90, "Ben": 75, "Cara": 88}. Two different names can have the same score: ["Zoe", "Adam"] with [60, 60] gives {"Zoe": 60, "Adam": 60}. Two empty arrays give an empty object.

    Approach

    The two arrays are linked by position: the name at index i belongs with the score at index i. A single index therefore reaches both, which calls for a counting loop, for (let i = 0; ...), rather than for...of. A for...of loop would give the names but not their positions.

    At each index, you add one entry to the result: assign the score to the key. Assigning to a key that is not in the object yet creates it, so no existence check is needed.

    Step by step

    1. Create an empty object named result with const.
    2. Write a for loop with let i = 0, the condition i < names.length and i++. The condition stops at the last valid index, names.length - 1.
    3. Add the pair with result[names[i]] = scores[i].
    4. Return result after the loop.

    The solution in JavaScript

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

    The line result[names[i]] = scores[i] has two index operations in different roles. names[i] is an array lookup that produces a string, and that string becomes the key inside the square brackets of result. On the right, scores[i] is the value. For i = 0 in the first example, the line works out to result["Ana"] = 90.

    The loop uses let for i because it changes on every pass, while result is a const that always refers to the same object. Adding keys to a const object is allowed. With two empty arrays, names.length is 0, the loop body never runs, and the function returns {}.

    Tracing the example

    For the first example, result starts as {}. After index 0 it is {Ana: 90}, after index 1 it is {Ana: 90, Ben: 75}, and after index 2 it is {Ana: 90, Ben: 75, Cara: 88}. Then i reaches 3, which is not less than 3, so the loop ends and the object is returned.

    A shorter form

    The same result comes from Object.fromEntries, which builds an object from an array of [key, value] pairs: Object.fromEntries(names.map((name, i) => [name, scores[i]])). For the first example this also gives {Ana: 90, Ben: 75, Cara: 88}. The loop does the same work step by step, which makes it the clearer version while you are learning how keys and values get paired.

    Edge cases and common mistakes

    • Repeated names. The lesson promises that names are all different. If one did repeat, the later score would overwrite the earlier one: ["Ana", "Ana"] with [1, 2] gives {Ana: 2}, with one entry.
    • Using result.names[i] or result.name. A dot reads or writes a key with that exact literal name. Use square brackets when the key comes from a variable or expression.
    • Off-by-one loop bounds. i <= names.length would run one extra time, with names[i] equal to undefined, and add an entry with the key "undefined".
    • Arrays of different lengths. The lesson guarantees equal lengths. If scores were shorter, the missing positions would give undefined values: ["Ana", "Ben"] with [1] gives {Ana: 1, Ben: undefined}.

    Testing

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