Start learning free

LESSON 251 OF 671 · NESTED LOOPS

Top K Brands V4 in JavaScript: Repeated Search

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

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

Build:

1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with console.log(...).

Start with the two declarations const used = new Array(ratings.length).fill(false); and const lines = [];. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

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

const used = new Array(ratings.length).fill(false);
const lines = [];
for (let rank = 1; rank <= k; rank++) {
    let bestIndex = -1;
    for (let i = 0; i < ratings.length; i++) {
        if (!used[i]) {
            if (bestIndex === -1 || ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    used[bestIndex] = true;
    lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
}
console.log(lines.join("\n"));

STEP 1 OF 11
    Ctrl + Enter to check

    JAVASCRIPT · NESTED LOOPS

    Top K Brands V4 in JavaScript, explained

    Problem overview

    Version 4 ranks the top k brands by rating. The data is in two parallel arrays, brands and ratings, where ratings[i] belongs to brands[i], and k says how many brands to show. Each output line has the form rank. Brand (rating), starting at rank 1.

    For the starter data, brands ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"] with ratings [4, 5, 3, 5, 4] and k = 3, the output is:

    1. MegaCorp (5)
    2. NeoByte (5)
    3. TechPro (4)
    

    MegaCorp and NeoByte both have rating 5, and MegaCorp is listed first, so it is rank 1. TechPro and Zenith tie at 4, and TechPro is listed first, so it takes rank 3. The lesson guarantees that k is never larger than the number of brands.

    Approach: find the best, mark it, repeat

    Version 3 found the single best brand with one scan. Version 4 repeats that scan once per rank. The only change is that a brand already placed must not win again, so the program keeps an array used, with one boolean per brand: used[i] is true after brand i has been given a rank.

    Each round starts with bestIndex = -1, meaning "nothing found yet". The inner loop looks at every brand that isn't used. The first one it sees becomes the best, and a later one replaces it only when its rating is strictly higher. Strictly higher is what makes ties go to the brand listed first. After the scan, the winner is marked as used and its line is added to an array lines.

    The cost is k scans of n brands: O(k * n) time, plus O(n) space for used. Sorting would be an alternative, but this lesson practises nested loops.

    The three rounds on the starter data

    rankBrands still availableWinner
    1all fiveMegaCorp (5): NeoByte ties at 5 but is not strictly higher
    2all but MegaCorpNeoByte (5)
    3TechPro, Quantum, ZenithTechPro (4): Zenith ties at 4 but is not strictly higher

    After round 3 the loop ends, and Quantum and Zenith never receive a rank because only k = 3 lines were asked for.

    Step by step

    1. Create used with one false per rating, using new Array(ratings.length).fill(false).
    2. Create lines as an empty array. One finished line will be added per round.
    3. Write the outer loop with rank from 1 up to and including k. Starting at 1 makes rank double as the number printed in front of the brand.
    4. Set bestIndex to -1 inside it, so every round starts the search over.
    5. Write the inner loop with i over every position of ratings.
    6. Skip used brands with if (!used[i]).
    7. Test for a new best: inside it, an if that is true when bestIndex is -1 or ratings[i] is strictly higher than ratings[bestIndex].
    8. Remember the brand by setting bestIndex to i.
    9. Mark the winner after the inner loop: used[bestIndex] = true.
    10. Add the line with push: the rank, a dot and a space, the brand's name, then the rating in parentheses.
    11. Print lines.join("\n") after the loops, so each line ends up on its own row.

    The solution in JavaScript

    const brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
    const ratings = [4, 5, 3, 5, 4];
    const k = 3;
    
    const used = new Array(ratings.length).fill(false);
    const lines = [];
    for (let rank = 1; rank <= k; rank++) {
        let bestIndex = -1;
        for (let i = 0; i < ratings.length; i++) {
            if (!used[i]) {
                if (bestIndex === -1 || ratings[i] > ratings[bestIndex]) {
                    bestIndex = i;
                }
            }
        }
        used[bestIndex] = true;
        lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
    }
    console.log(lines.join("\n"));
    

    The details to notice:

    • new Array(n).fill(false). new Array(n) alone makes empty slots. fill(false) gives each a real false.
    • Building text with +. When one side is a string, JavaScript converts the number on the other side, so rank + ". " + ... produces "1. MegaCorp (5)". The first + has a number on its left and a string on its right, so it joins rather than adds.
    • join("\n"). It glues the array's strings together with a newline between each pair, with none after the last one. A single console.log then prints every rank on its own line.
    • Collect, then print once. The lines are stored in an array and printed together at the end, instead of printing inside the loop. The program then produces its whole output in one console.log call, and you could still sort, count or check the lines before printing them.
    • bestIndex holds a position, not a value. The position works in both arrays, so one variable gives the name and the rating.

    Edge cases and common mistakes

    • Ties. Using >= instead of > makes the later brand replace the earlier one. For the starter data NeoByte would take rank 1 instead of MegaCorp.
    • Forgetting to mark the winner. Without used[bestIndex] = true, every round would return MegaCorp.
    • Placing bestIndex = -1 before the outer loop. The previous winner's index would carry into the next round, and the search would not start from scratch.
    • k equal to the number of brands. With k = 5 every brand gets a rank, from MegaCorp, NeoByte, TechPro and Zenith down to Quantum.
    • k larger than the number of brands. The lesson promises this doesn't happen. If it did, bestIndex would stay -1 in the extra rounds, and the program would print a line such as 6. undefined (undefined).
    • k = 0. The loop doesn't run, lines is empty, and join gives an empty string, so a blank line is printed.

    Testing

    • The starter data with k = 3 prints MegaCorp (5), NeoByte (5) and TechPro (4) as ranks 1 to 3.
    • k = 1 prints only 1. MegaCorp (5).
    • k = 5 prints MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3).
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free