Many brands sell the same product, stored in two parallel arrays: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.
You start with:
const brands: string[] = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings: number[] = [4, 5, 3, 5, 4];
Build:
1. MegaCorp (5)
Rules:
- Keep the position of the best brand so far in
bestIndex, starting at0, and scan the positions from1to the end with a loop. - Update
bestIndexonly on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorpat position 1, notNeoByteat position 3). - Format the winner as
"1. Brand (rating)"and print it withconsole.log(...).
Walk the positions with
for (let i: number = 1; i < ratings.length; i++) { and compare each rating with the best one so far.
TypeScript turns the number into text for you when you join it to a string with
+.
const brands: string[] = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings: number[] = [4, 5, 3, 5, 4];
let bestIndex: number = 0;
for (let i: number = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[bestIndex]) {
bestIndex = i;
}
}
console.log("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
