Start learning free

LESSON 167 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 - Group by Category in TypeScript

Practice

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 totals that 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 (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with console.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);

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V6 in TypeScript

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free