Start learning free

LESSON 255 OF 289 · NESTED LOOPS

Top K Brands V5 in TypeScript: Filter Rows, Then Rank the Top K

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: string[] = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
const ratings: number[] = [4, 5, 5, 3, 4, 4];
const target: string = "Laptop";
const k: number = 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: string[] = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
const ratings: number[] = [4, 5, 5, 3, 4, 4];
const target: string = "Laptop";
const k: number = 2;

const filteredBrands: string[] = [];
const filteredRatings: number[] = [];
for (let i = 0; i < products.length; i++) {
    if (products[i] === target) {
        filteredBrands.push(brands[i]);
        filteredRatings.push(ratings[i]);
    }
}
const used: boolean[] = new Array(filteredRatings.length).fill(false);
const lines: string[] = [];
for (let rank = 1; rank <= k; rank++) {
    let bestIndex: number = -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

    TYPESCRIPT · NESTED LOOPS

    Top K Brands V5 in TypeScript, explained

    Problem overview

    The catalog now covers several products. Three parallel arrays describe it: row i is one product, products[i], sold by the brand brands[i], with the rating ratings[i]. The constant target names the product of interest, and k says how many brands to list.

    The program first keeps only the rows whose product equals target, then prints the top k of those brands by rating, best first, as rank. Brand (rating). Ties go to the entry listed first. If fewer than k rows match, only the existing brands are listed, with no extra lines.

    In the starting data the target is "Laptop" and k is 2. The laptop rows are TechPro (4), NeoByte (5) and AlphaTech (4), so the output is:

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

    Approach: filter first, then repeat the search

    The work splits into two stages.

    Filtering. One loop over the whole catalog copies the brand and the rating of each matching row into two new arrays, filteredBrands and filteredRatings. The two arrays are filled together, in the original order, so a brand and its rating stay at the same position.

    Ranking. After filtering, the problem is the one from the previous version, on shorter arrays. For each rank from 1 to k the program scans every filtered entry, skips the ones already used, and keeps the position of the best rating so far. A strict "greater than" keeps the earlier entry on a tie. It then marks the winner as used and adds a line.

    The one new condition is for matches running out. If only two rows match and k is 3, the third round finds nothing, and bestIndex stays at -1. The program adds a line only when it found a brand.

    Tracing the starting data: the filter keeps rows 0, 2 and 5, so filteredBrands is ["TechPro", "NeoByte", "AlphaTech"] and filteredRatings is [4, 5, 4]. Round 1 picks NeoByte (5). Round 2 skips NeoByte. TechPro (4) is reached first, and AlphaTech's 4 isn't strictly greater, so TechPro wins the second place.

    Step by step

    1. Create the filtered brands. An empty string[] named filteredBrands.
    2. Create the filtered ratings. An empty number[] named filteredRatings. Both arrays will stay in step, position by position.
    3. Loop over the catalog. A for loop where i takes each position of products. The three starting arrays line up, so row i is one product with its brand and rating.
    4. Test the product. Inside the loop, an if for products[i] === target. Other rows are skipped.
    5. Copy the brand, with push, into filteredBrands.
    6. Copy the rating the same way into filteredRatings, so the pair stays aligned.
    7. Create the flags. A boolean[] named used, with a false for each filtered rating. The search runs on the filtered arrays, so the flags are as long as they are.
    8. Create the output list. An empty string[] named lines.
    9. Write the rank loop, with rank from 1 up to and including k.
    10. Reset the best. Inside it, bestIndex starts at -1.
    11. Write the inner loop over every position of filteredRatings.
    12. Skip used entries with an if on used[i] being false.
    13. Compare. Inside it, a second if: nothing found yet, or a strictly higher rating.
    14. Remember the position by setting bestIndex to i.
    15. Check that something was found. After the inner loop, an if for bestIndex not equal to -1.
    16. Mark the winner by setting used[bestIndex] to true.
    17. Add the line to lines with push: the rank, a dot and a space, the brand's name and the rating in parentheses, all from the filtered arrays.
    18. Print. After the loop, lines.join("\n") inside console.log.

    The solution in TypeScript

    const products: string[] = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
    const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
    const ratings: number[] = [4, 5, 5, 3, 4, 4];
    const target: string = "Laptop";
    const k: number = 2;
    
    const filteredBrands: string[] = [];
    const filteredRatings: number[] = [];
    for (let i = 0; i < products.length; i++) {
        if (products[i] === target) {
            filteredBrands.push(brands[i]);
            filteredRatings.push(ratings[i]);
        }
    }
    const used: boolean[] = new Array(filteredRatings.length).fill(false);
    const lines: string[] = [];
    for (let rank = 1; rank <= k; rank++) {
        let bestIndex: number = -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"));
    

    Details worth knowing:

    • === on strings. products[i] === target compares the text itself, and it is case-sensitive: "Laptop" and "laptop" are different values.
    • push. It adds a value at the end of an array and changes the array in place. That is why filteredBrands and filteredRatings can be const: the variable never points to a different array.
    • Loop variable names. The two i variables belong to separate loops, so they don't clash.
    • !=. The solution compares with !=, which for two numbers behaves the same as !==.
    • Joining the lines. If lines is empty, join("\n") returns an empty string, and console.log prints an empty line.

    Complexity

    Time: O(n + k * m), where n is the number of catalog rows and m the number of rows that match. Filtering is one pass over n rows. Ranking is k scans of m entries.

    Space: O(m). The filtered arrays and used each hold m entries, and lines holds at most min(k, m) strings.

    Edge cases and common mistakes

    • Fewer matches than k. With k = 5 and "Laptop", only three rows match, and the program prints three lines: NeoByte (5), TechPro (4) and AlphaTech (4). A target with one row works too: "Tablet" with k = 3 prints only 1. Quantum (3).
    • Removing the check on bestIndex. With k = 5 and the laptop rows, the program would also print 4. undefined (undefined) and 5. undefined (undefined). Reading position -1 of an array gives undefined and no error.
    • No matching rows. A target such as "Camera" prints one empty line, since there are no lines to join. A target in a different case, such as "laptop", behaves the same way, because the comparison is case-sensitive.
    • Another product. With "Phone" and k = 2 the output is 1. MegaCorp (5) and 2. Zenith (4).
    • Mixing up the arrays. The ranking must read filteredBrands and filteredRatings. Using brands or ratings inside it would index the full catalog with positions that belong to the filtered arrays.
    • Copying only one of the two values. If the filter pushes the brand but not the rating, the arrays go out of step and the ratings no longer belong to the brands.

    Testing

    • The starting data prints 1. NeoByte (5) and 2. TechPro (4).
    • "Laptop" with k = 5 prints NeoByte (5), TechPro (4) and AlphaTech (4), numbered 1 to 3.
    • "Phone" with k = 2 prints 1. MegaCorp (5) and 2. Zenith (4).
    • "Tablet" with k = 3 prints 1. Quantum (3).
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free