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
targetinto two new lists, keeping the order. - From the filtered lists pick the top
kby rating, highest first, with v4's repeated search. Ties go to the entry listed first. - If fewer than
kproducts 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"));
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
