Start learning free

LESSON 252 OF 671 · NESTED LOOPS

Top K Brands V5 in JavaScript: Filter, Then Rank

Practice Read the full explanation

The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.

You start with:

const products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
const brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
const ratings = [4, 5, 5, 3, 4, 4];
const target = "Laptop";
const k = 2;

Build:

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

Rules:

  • Filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the order.
  • From the filtered lists pick the top k by rating, highest first, with v4's repeated search. Ties go to the entry listed first.
  • If fewer than k products match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error).
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with console.log(...).

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products[i] === target.

Then run v4's repeated search over the filtered lists (same code, new names).

If fewer than k products match, some round finds nobody (bestIndex stays -1): add a line only when a brand was found.

const products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
const brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
const ratings = [4, 5, 5, 3, 4, 4];
const target = "Laptop";
const k = 2;

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

STEP 1 OF 18
    Ctrl + Enter to check

    JAVASCRIPT · NESTED LOOPS

    Top K Brands V5 in JavaScript, explained

    Problem overview

    The catalog now covers several products. Three parallel arrays describe it: products[i] is the product, brands[i] the brand that sells it and ratings[i] its rating. A variable target names the product of interest, and k says how many brands to rank.

    The program first filters the catalog down to the rows whose product equals target, then ranks the top k of those brands using version 4's repeated search. For target = "Laptop" and k = 2 the output is:

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

    Three rows sell a Laptop: TechPro (4), NeoByte (5) and AlphaTech (4). NeoByte has the top rating. TechPro and AlphaTech tie at 4, and TechPro is listed first. If fewer than k brands sell the product, only the brands that exist are printed, with no error and no extra lines.

    Approach: two phases

    Phase 1, the filter. Walk through every row. When products[i] equals target, copy that row's brand and rating into two new arrays, filteredBrands and filteredRatings. The two arrays are filled together, so they stay aligned: the same position in both describes the same brand.

    Phase 2, the ranking. This is version 4's search, run on the filtered arrays instead of the originals. Each round finds the best brand that isn't used, marks it as used and adds its line. One change is needed because the filtered arrays can be shorter than k: when a round finds nobody, bestIndex stays -1, and the round must add no line.

    The filter keeps the original order, which matters for ties. Because TechPro comes before AlphaTech in the catalog, it also comes before it in the filtered arrays, and the strict comparison keeps it ahead.

    Step by step

    1. Create filteredBrands as an empty array for the brands that sell the target product.
    2. Create filteredRatings as an empty array for their ratings.
    3. Loop over the catalog with i taking every position of products.
    4. Test the product. Inside the loop, an if that is true when products[i] equals target.
    5. Copy the brand into filteredBrands with push.
    6. Copy the rating into filteredRatings the same way, so the two arrays stay in step.
    7. Create used after the loop, one false per filtered rating. It is as long as the filtered arrays, not the original ones.
    8. Create lines as an empty array.
    9. Write the ranking loop with rank from 1 to k inclusive.
    10. Set bestIndex to -1 at the top of each round.
    11. Write the inner loop over every position of filteredRatings.
    12. Skip used brands with if (!used[i]).
    13. Test for a new best: bestIndex is -1, or this rating is strictly higher than the best one's.
    14. Remember it: set bestIndex to i.
    15. Check that a brand was found after the inner loop: bestIndex is not -1.
    16. Mark it as used with used[bestIndex] = true.
    17. Push the line: the rank, a dot and a space, the brand and the rating in parentheses.
    18. Print the lines joined with newlines.

    The solution in JavaScript

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

    The details to notice:

    • === compares strings by content. products[i] === target is true only for an exact match, including case: with target = "laptop" nothing matches and the output is empty.
    • Positions change after filtering. In the filtered arrays NeoByte sits at position 1, not at position 2 as in the catalog. That is why the ranking loop works only with the filtered arrays and reads the brand name from filteredBrands.
    • != against !==. The lesson's solution uses bestIndex != -1. For numbers it behaves like !==, and !== is the habit worth keeping, because the loose form converts types before comparing.
    • push adds at the end. Brand and rating are pushed together in the same iteration, so they can never fall out of step.
    • Empty lines. [].join("\n") is the empty string, so with no matches the program prints one blank line.

    Edge cases and common mistakes

    • Fewer matches than k. For target = "Tablet" and k = 3, only Quantum sells a Tablet, so the output is the single line 1. Quantum (3). The rounds 2 and 3 find nobody and add nothing.
    • No matches at all. target = "Watch" gives empty filtered arrays and a blank output.
    • k larger than the matches. For target = "Laptop" with k = 3 or k = 5, the output is NeoByte (5), TechPro (4) and AlphaTech (4). Without the bestIndex check the extra rounds would add a line such as 4. undefined (undefined).
    • Indexing the original arrays with a filtered position. Reading brands[bestIndex] instead of filteredBrands[bestIndex] would print the wrong brand, because the positions no longer match.
    • Case. "Laptop" and "laptop" are different strings.

    Testing

    • target = "Laptop", k = 2 gives 1. NeoByte (5) and 2. TechPro (4).
    • target = "Laptop", k = 3 adds 3. AlphaTech (4).
    • target = "Phone", k = 2 gives 1. MegaCorp (5) and 2. Zenith (4).
    • target = "Tablet", k = 3 gives 1. Quantum (3).
    • target = "Watch" prints an empty line.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free