Start learning free

LESSON 194 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in TypeScript: Totals per Category

Practice Read the full explanation

Use an 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 an 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

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in TypeScript, explained

    Problem overview

    The cart is described by three parallel arrays: items, prices and categories. The item at index 0 is an Apple that costs 2 and belongs to Food, the item at index 2 is a Shirt that costs 25 and belongs to Clothes, and so on. The program must add up the prices per category and print one line for each category in the form Category: $total, sorted alphabetically by category name, joined by newlines into result.

    Clothes: $65
    Food: $6

    Food gets 2 + 3 + 1 = 6 from Apple, Bread and Banana, and Clothes gets 25 + 40 = 65 from Shirt and Pants. The categories are not known in advance, which is why an object that grows as the loop discovers them fits the job.

    Approach: accumulate in an object, then sort the keys

    An object whose keys are category names and whose values are running totals is the right accumulator. The loop looks at each item, finds its category, and adds the item's price to that category's total. The first time a category appears it has no entry yet, so reading it gives undefined. The expression (totals[cat] || 0) replaces that undefined with 0, so the first addition starts from zero.

    An object does not promise a convenient order for printing, so the program collects the keys with Object.keys(totals), sorts them, and builds the lines by walking the sorted keys. Sorting keys instead of rows means the totals never have to move.

    On the starter data the object changes like this as the loop runs:

    iitemcategorytotals after
    0AppleFoodFood 2
    1BreadFoodFood 5
    2ShirtClothesFood 5, Clothes 25
    3BananaFoodFood 6, Clothes 25
    4PantsClothesFood 6, Clothes 65

    Step by step

    1. Create totals as an empty object typed Record<string, number>: string keys, number values.
    2. Loop over the positions with for (let i = 0; i < items.length; i++) so the same index reaches prices and categories. Close the brace right away.
    3. Read the category into cat: categories[i].
    4. Update the total: assign (totals[cat] || 0) + prices[i] to totals[cat]. The || 0 handles a category seen for the first time.
    5. After the loop, create lines as an empty string[].
    6. Get the sorted keys: Object.keys(totals).sort() returns the category names as an array and sorts it.
    7. Loop over the keys with for (const cat of keys). Close the brace right away.
    8. Push one row per category: the name, a colon and space, a dollar sign and the total.
    9. Join the rows with "\n" into result, so there is no newline after the last row.
    10. Print result.

    The solution in TypeScript

    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);

    Language details worth knowing:

    • sort() without a comparator sorts as strings, comparing UTF-16 code units. For category names that means every capital letter comes before every lower-case one. With the keys ["Food", "clothes", "Books", "Toys"] the default sort gives Books, Food, Toys, clothes. Sorting with (a, b) => a.localeCompare(b) gives Books, clothes, Food, Toys. The lesson's categories all start with a capital letter, so the plain sort() is enough.
    • sort() sorts the array in place and also returns it. That is safe here, because Object.keys creates a fresh array each time it is called.
    • for...of over an array gives the values, not the indexes, which is what the second loop needs. The first loop needs the index, so it uses the classic form.
    • Why || 0 is acceptable here. The only falsy value that could be stored is a total of 0, and replacing 0 by 0 changes nothing.

    Complexity

    The first loop does constant work per item, so O(n) for n items. Sorting the k distinct categories costs O(k log k), and building the rows is O(k). The total is O(n + k log k), and the object uses O(k) extra space, plus O(k) for the rows.

    Edge cases and common mistakes

    • Starting from totals[cat] + prices[i]. For a new category that is undefined + 2, which is NaN, and the category would stay NaN for the rest of the run.
    • Different spellings of the same category. Keys are case-sensitive, so Food and food are two categories. With lower-case clothes in the data, the starter prices give Food: $6 first and clothes: $65 second, because capitals sort first.
    • Printing in insertion order. Iterating the object directly would list Food before Clothes, the order in which they were first seen. The task asks for alphabetical order, so sort the keys.
    • A zero price is fine: with the Apple at price 0, the output is Clothes: $65 and Food: $4.
    • A category named like a built-in property. An object literal inherits properties such as constructor. With a category named constructor the program prints a line like constructor: $function Object() { [native code] }25, because the lookup finds the inherited function instead of undefined. A Map doesn't have this problem, and Object.create(null) gives an object without inherited keys.

    Testing

    Try these changes in the editor above. The results come from the reference solution:

    • Setting the Apple's price to 0 prints Clothes: $65 and Food: $4.
    • Changing "Clothes" to "clothes" in categories prints Food: $6 and then clothes: $65.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free