Use a object to accumulate totals per category while looping over parallel arrays, then list the categories sorted by name.
You start with:
const items: string[] = ["Apple", "Bread", "Shirt", "Banana", "Pants"];
const prices: number[] = [2, 3, 25, 1, 40];
const categories: string[] = ["Food", "Food", "Clothes", "Food", "Clothes"];
Build:
Clothes: $65 Food: $6
Rules:
- Build a object
totalsthat maps each category to the sum of the prices of its items. - Loop with an index. For each item, add its price to the total of
categories[i]; a category you have not seen yet counts as 0. - Make one line per category, in the format
"Category: $total", sorted alphabetically by category name (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult, then print it withconsole.log(result).
Use
(totals[cat] || 0) + prices[i] to default missing keys to 0.
Object.keys(totals).sort() gives the keys in alphabetical order.
const items: string[] = ["Apple", "Bread", "Shirt", "Banana", "Pants"];
const prices: number[] = [2, 3, 25, 1, 40];
const categories: string[] = ["Food", "Food", "Clothes", "Food", "Clothes"];
const totals: Record<string, number> = {};
for (let i = 0; i < items.length; i++) {
const cat: string = categories[i];
totals[cat] = (totals[cat] || 0) + prices[i];
}
const lines: string[] = [];
const keys: string[] = Object.keys(totals).sort();
for (const cat of keys) {
lines.push(cat + ": $" + totals[cat]);
}
const result: string = lines.join("\n");
console.log(result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
