Start learning free

LESSON 262 OF 671 · DESTRUCTURING, SORTING & BUILT-INS

Oldest Pet in JavaScript: Looping Over Pairs

Practice Read the full explanation

You get an array of pets, pets. Each pet is a pair: its name and its age, like ("Rex", 4).

Return the name of the oldest pet.

Several pets may share the oldest age. Then return the one that comes first in pets.

The starter code shows how your language holds a pair.

 

Example 1:

Input: pets = [("Rex", 4), ("Bella", 7), ("Max", 2)]
Output: "Bella"
Explanation: Bella is 7.
Rex and Max are younger.

Example 2:

Input: pets = [("Luna", 3), ("Coco", 9), ("Milo", 9)]
Output: "Coco"
Explanation: Coco and Milo are both 9.
Coco comes first in the list.

Example 3:

Input: pets = [("Kiki", 0)]
Output: "Kiki"
Explanation: Kiki is the only pet.

 

Constraints:

  • pets has at least one pet.
  • Every age is a whole number from 0 to 30.
  • Each name is a capital letter followed by lowercase letters, like "Rex".
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · DESTRUCTURING, SORTING & BUILT-INS

    Oldest Pet in JavaScript, explained

    Problem overview

    oldestPet(pets) receives an array of pets. Each pet is a two-item array, [name, age], such as ["Rex", 4]. The function returns the name of the oldest pet. If several pets share the oldest age, it returns the one that comes first.

    For [["Rex", 4], ["Bella", 7], ["Max", 2]] the answer is "Bella". For [["Luna", 3], ["Coco", 9], ["Milo", 9]] the answer is "Coco", because Coco and Milo are both 9 and Coco is first.

    Approach

    Remember the oldest pet seen so far, and compare each pet with it. Keep the whole pair, not just the age, so the name comes along. A pet's age is at index 1 and its name at index 0.

    The tie rule comes from the comparison. Replace the stored pet only when the new one is strictly older (>). On a tie the stored pet, which came earlier, stays. Using >= would let a later pet win a tie.

    Step by step

    1. Set oldest to pets[0]. It is the oldest pet seen so far, before the loop looks at the others.
    2. Loop over pets with for...of; each item is one pair, pet.
    3. If pet[1] > oldest[1], this pet is older.
    4. Then set oldest = pet.
    5. After the loop, return oldest[0], the name.

    The solution in JavaScript

    class Solution {
        oldestPet(pets) {
            let oldest = pets[0];
            for (let pet of pets) {
                if (pet[1] > oldest[1]) {
                    oldest = pet;
                }
            }
            return oldest[0];
        }
    }
    

    In JavaScript the pair is an array, so the pairs are written with square brackets. The first loop pass compares pets[0] with itself, which changes nothing. Running the three examples returns Bella, Coco and Kiki (for [["Kiki", 0]]).

    Tracing the tie example

    For [["Luna", 3], ["Coco", 9], ["Milo", 9]], this is the name of oldest after each pet is checked:

    Luna -> oldest=Luna
    Coco -> oldest=Coco
    Milo -> oldest=Coco
    

    Coco's 9 beats Luna's 3, so Coco replaces Luna. Milo's 9 is not greater than Coco's 9, so Coco stays. If the test were >=, Milo would replace Coco and the function would return "Milo", which fails the lesson's tests.

    Complexity

    Each pet is compared once, so the time is O(n) for n pets. The function stores only one pair at a time, so the extra space is O(1). Sorting the pets by age and taking the end would also find the answer, but it does more work than one pass needs.

    Edge cases and common mistakes

    • A single pet. The loop never replaces oldest, and the first pet's name is returned. An age of 0 is fine.
    • Ties. Use >, not >=, to keep the first of equal ages.
    • Tracking only the age. A variable holding just the biggest age tells you how old the oldest pet is, but not whose name to return. Keeping the pair solves that.
    • Returning the pair. The function returns only the name, oldest[0].
    • Swapped indexes. Comparing pet[0] would compare names, not ages. Strings compare alphabetically, so "Rex" > "Bella" is true, and the first example would return "Rex" instead of "Bella", with no error to point at the mistake.
    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free