Start learning free

LESSON 252 OF 285 · NESTED LOOPS

Top K Brands V6 in JavaScript: Tie-Break by Review Count

Practice Read the full explanation

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

const brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
const ratings = [4, 5, 5, 3, 4];
const reviews = [200, 150, 500, 100, 300];
const k = 3;

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Print the lines, one per line, with console.log(...).

Start from v4: the same const used = new Array(ratings.length).fill(false); and const lines = [];, the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

const brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
const ratings = [4, 5, 5, 3, 4];
const reviews = [200, 150, 500, 100, 300];
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) {
                bestIndex = i;
            }
            else if (ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
            else if (ratings[i] === ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    used[bestIndex] = true;
    lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
}
console.log(lines.join("\n"));

STEP 1 OF 12
    Ctrl + Enter to check

    JAVASCRIPT · NESTED LOOPS

    Top K Brands V6 in JavaScript, explained

    Problem overview

    Version 6 ranks the top k brands by rating and uses the review count to break ties. There are three parallel arrays, brands, ratings and reviews, and a number k. Each output line has the form rank. Brand (rating, reviews).

    The rules are, in order: the higher rating wins; if the ratings are equal, the brand with more reviews wins; if both are equal, the brand listed first wins. For the starter data (ratings [4, 5, 5, 3, 4], reviews [200, 150, 500, 100, 300], k = 3) the output is:

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)
    

    MegaCorp and NeoByte tie at 5, and NeoByte has more reviews, so it comes first. TechPro and Zenith tie at 4, and Zenith's 300 reviews beat TechPro's 200. This version builds on version 4's repeated search, with no filtering. Only the comparison changes. The lesson guarantees k is never larger than the number of brands.

    Approach: a comparison with two criteria

    The structure is the same as in version 4. An array used marks the brands that already have a rank, and each round scans the brands that aren't used, remembering the position of the best in bestIndex. What changes is the test for "this brand beats the current best". It is now a chain of cases, checked in order:

    1. Nothing has been found yet (bestIndex is -1): this brand is the best so far.
    2. This brand's rating is higher than the best one's: it wins, and the reviews don't matter.
    3. The ratings are equal and this brand has more reviews: it wins.

    If none of the cases is true, the current best stays. That includes the case where rating and reviews are both equal, so the brand listed first keeps its place, because the comparisons are strict.

    Step by step

    1. Create used with one false per rating.
    2. Create lines as an empty array.
    3. Write the outer loop with rank from 1 up to and including k.
    4. Set bestIndex to -1 at the start of each round.
    5. Write the inner loop over every position of ratings.
    6. Skip used brands: an if that is true when used[i] is false.
    7. First case: if bestIndex is -1, set it to i. The first brand not used has nothing to beat.
    8. Second case: an else if for a higher rating. It runs only when the case above was false, and a higher rating decides before reviews are looked at.
    9. Third case: an else if where the ratings are equal and this brand has more reviews. Both conditions must hold, joined by &&.
    10. Mark the winner after the inner loop: used[bestIndex] = true.
    11. Push the line: rank, a dot and a space, the name, then the rating and the review count in parentheses, separated by a comma and a space.
    12. Print the lines joined with newlines.

    The solution in JavaScript

    const brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
    const ratings = [4, 5, 5, 3, 4];
    const reviews = [200, 150, 500, 100, 300];
    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) {
                    bestIndex = i;
                }
                else if (ratings[i] > ratings[bestIndex]) {
                    bestIndex = i;
                }
                else if (ratings[i] === ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                    bestIndex = i;
                }
            }
        }
        used[bestIndex] = true;
        lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
    }
    console.log(lines.join("\n"));
    

    The details to notice:

    • Order of the cases. The bestIndex === -1 case comes first, so the later cases never read ratings[-1], which would be undefined.
    • An else if chain runs at most one branch. A brand with a higher rating is accepted by case 2, and case 3 is never tested for it.
    • Why the rating check stays in case 3. Without ratings[i] === ratings[bestIndex], a brand with more reviews but a lower rating would replace the best one. With brands ["A", "B"], ratings [5, 4] and reviews [10, 99], A is the right winner, but a version that drops the equality test picks B.
    • === for equal ratings. Both are numbers, so === compares the values with no conversions.
    • Several values in a line. ", " is inserted by hand between the rating and the review count, giving (5, 500).

    Edge cases and common mistakes

    • Full ties. With brands A, B and C, ratings [5, 5, 4] and reviews [10, 10, 99], A and B tie on both numbers. Neither strict comparison replaces the other, so A ranks first and B second, as the rules say.
    • Using >= for reviews. In the same example, >= lets B replace A, so B would rank first.
    • Reviews settle only ties. With k = 1, ratings [3, 3] and reviews [5, 50], the ratings tie, so the second brand wins: 1. Y (3, 50) for brands X and Y.
    • Forgetting to mark the winner. Each round would find NeoByte again.
    • k = 5 for the starter data. The ranking continues down to the fourth and fifth places: TechPro (4, 200), then Quantum (3, 100).

    Testing

    • The starter data with k = 3 prints NeoByte (5, 500), MegaCorp (5, 150) and Zenith (4, 300).
    • The same data with k = 5 adds 4. TechPro (4, 200) and 5. Quantum (3, 100).
    • Brands ["A", "B", "C"], ratings [5, 5, 4], reviews [10, 10, 99], k = 3 prints 1. A (5, 10), 2. B (5, 10) and 3. C (4, 99).
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free