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
- Create
filteredBrandsas an empty array for the brands that sell the target product. - Create
filteredRatingsas an empty array for their ratings. - Loop over the catalog with
itaking every position ofproducts. - Test the product. Inside the loop, an
ifthat is true whenproducts[i]equalstarget. - Copy the brand into
filteredBrandswithpush. - Copy the rating into
filteredRatingsthe same way, so the two arrays stay in step. - Create
usedafter the loop, onefalseper filtered rating. It is as long as the filtered arrays, not the original ones. - Create
linesas an empty array. - Write the ranking loop with
rankfrom 1 tokinclusive. - Set
bestIndexto -1 at the top of each round. - Write the inner loop over every position of
filteredRatings. - Skip used brands with
if (!used[i]). - Test for a new best:
bestIndexis -1, or this rating is strictly higher than the best one's. - Remember it: set
bestIndextoi. - Check that a brand was found after the inner loop:
bestIndexis not -1. - Mark it as used with
used[bestIndex] = true. - Push the line: the rank, a dot and a space, the brand and the rating in parentheses.
- 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] === targetis true only for an exact match, including case: withtarget = "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 usesbestIndex != -1. For numbers it behaves like!==, and!==is the habit worth keeping, because the loose form converts types before comparing.pushadds 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. Fortarget = "Tablet"andk = 3, only Quantum sells a Tablet, so the output is the single line1. 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. klarger than the matches. Fortarget = "Laptop"withk = 3ork = 5, the output is NeoByte (5), TechPro (4) and AlphaTech (4). Without thebestIndexcheck the extra rounds would add a line such as4. undefined (undefined).- Indexing the original arrays with a filtered position. Reading
brands[bestIndex]instead offilteredBrands[bestIndex]would print the wrong brand, because the positions no longer match. - Case.
"Laptop"and"laptop"are different strings.
Testing
target = "Laptop",k = 2gives1. NeoByte (5)and2. TechPro (4).target = "Laptop",k = 3adds3. AlphaTech (4).target = "Phone",k = 2gives1. MegaCorp (5)and2. Zenith (4).target = "Tablet",k = 3gives1. Quantum (3).target = "Watch"prints an empty line.
