Start learning free

LESSON 184 OF 285 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in JavaScript: Best Rating in an Array

Practice Read the full explanation

Many brands sell the same product, stored in two parallel arrays: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

const brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings = [4, 5, 3, 5, 4];

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with console.log(...).

Walk the positions with for (let i = 1; i < ratings.length; i++) { and compare each rating with the best one so far.

JavaScript turns the number into text for you when you join it to a string with +.

const brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings = [4, 5, 3, 5, 4];

let bestIndex = 0;
for (let i = 1; i < ratings.length; i++) {
    if (ratings[i] > ratings[bestIndex]) {
        bestIndex = i;
    }
}
console.log("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in JavaScript, explained

    Problem overview

    In version 2, two brands lived in separate variables. Version 3 stores many brands in two parallel arrays: ratings[i] is the rating of brands[i]. The program scans the arrays to find the highest-rated brand and prints it as 1. Brand (rating). If two brands share the top rating, the one listed first wins.

    In the starter data, MegaCorp (position 1) and NeoByte (position 3) both have rating 5. MegaCorp is listed first, so the output is:

    1. MegaCorp (5)
    

    Approach

    This is the standard scan for a maximum. Keep the position of the best brand found so far, start with position 0, and look at each later position once. When a brand has a strictly higher rating than the current best, it takes over. At the end, bestIndex holds the position of the winner.

    The lesson keeps the position instead of the rating itself. The position works in both arrays, so brands[bestIndex] gives the name and ratings[bestIndex] gives the rating. Keeping only the rating would lose the brand's name.

    Step by step

    1. Create bestIndex with let and set it to 0. For now the first brand is the best one known.
    2. Write the loop. for (let i = 1; i < ratings.length; i++) visits positions 1 to the last one. It starts at 1 because position 0 is the starting best. The upper bound is ratings.length, and < stops before it, since the last valid position is one less than the length.
    3. Compare. Inside the loop, test ratings[i] > ratings[bestIndex]. It is strict, so a brand with an equal rating doesn't replace the earlier one.
    4. Update. Inside the if, set bestIndex to i.
    5. Print after the loop the line built from the rank "1. ", brands[bestIndex], " (", ratings[bestIndex] and ")".

    The solution in JavaScript

    const brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
    const ratings = [4, 5, 3, 5, 4];
    
    let bestIndex = 0;
    for (let i = 1; i < ratings.length; i++) {
        if (ratings[i] > ratings[bestIndex]) {
            bestIndex = i;
        }
    }
    console.log("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
    

    Some details:

    • The two arrays are linked only by position. Nothing in the language ties brands[1] to ratings[1]; the program relies on both arrays being in the same order.
    • The console.log is outside the loop, so it runs once. Placing it inside would print a line for every improvement.
    • The loop variable i is declared in the for header and disappears when the loop ends. bestIndex is declared before the loop, so the final line can use it.
    • The array length is 5, and the valid positions are 0 to 4. Reading ratings[5] gives undefined and no error.

    Complexity

    Time: O(n) for n brands. The loop makes one comparison per brand. Space: O(1), because only bestIndex and the loop counter are stored, however long the arrays are.

    Tracing the starter data

    The ratings are [4, 5, 3, 5, 4] and bestIndex starts at 0. At i = 1, 5 beats 4, so bestIndex becomes 1. At i = 2, 3 doesn't beat 5. At i = 3, 5 doesn't beat 5, because the comparison is strict, so NeoByte doesn't replace MegaCorp. At i = 4, 4 doesn't beat 5. The result is position 1, 1. MegaCorp (5).

    Edge cases and common mistakes

    • Using >=. A later brand with an equal rating would take over, and the output would show NeoByte.
    • Looping to i <= ratings.length. The last pass reads past the end of the array.
    • Keeping the best rating instead of its position. The name can't then be found.
    • All ratings equal. No brand beats the first, so position 0 wins.
    • A single brand. The loop body never runs, and the first brand is printed.
    • Empty arrays. brands[0] is undefined, so the line would show undefined. The lesson's data always has brands.

    Testing

    • Ratings [1, 2, 3] give the last brand.
    • Ratings [3, 2, 1] give the first brand.
    • Ratings [2, 2, 2] give the first brand.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free