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:
| i | item | category | totals after |
|---|---|---|---|
| 0 | Apple | Food | Food 2 |
| 1 | Bread | Food | Food 5 |
| 2 | Shirt | Clothes | Food 5, Clothes 25 |
| 3 | Banana | Food | Food 6, Clothes 25 |
| 4 | Pants | Clothes | Food 6, Clothes 65 |
Step by step
- Create
totalsas an empty object typedRecord<string, number>: string keys, number values. - Loop over the positions with
for (let i = 0; i < items.length; i++)so the same index reachespricesandcategories. Close the brace right away. - Read the category into
cat:categories[i]. - Update the total: assign
(totals[cat] || 0) + prices[i]tototals[cat]. The|| 0handles a category seen for the first time. - After the loop, create
linesas an emptystring[]. - Get the sorted keys:
Object.keys(totals).sort()returns the category names as an array and sorts it. - Loop over the keys with
for (const cat of keys). Close the brace right away. - Push one row per category: the name, a colon and space, a dollar sign and the total.
- Join the rows with
"\n"intoresult, so there is no newline after the last row. - 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 givesBooks, Food, Toys, clothes. Sorting with(a, b) => a.localeCompare(b)givesBooks, clothes, Food, Toys. The lesson's categories all start with a capital letter, so the plainsort()is enough.sort()sorts the array in place and also returns it. That is safe here, becauseObject.keyscreates a fresh array each time it is called.for...ofover 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
|| 0is 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 isundefined + 2, which isNaN, and the category would stayNaNfor the rest of the run. - Different spellings of the same category. Keys are case-sensitive, so
Foodandfoodare two categories. With lower-caseclothesin the data, the starter prices giveFood: $6first andclothes: $65second, because capitals sort first. - Printing in insertion order. Iterating the object directly would list
FoodbeforeClothes, 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: $65andFood: $4. - A category named like a built-in property. An object literal inherits properties such as
constructor. With a category namedconstructorthe program prints a line likeconstructor: $function Object() { [native code] }25, because the lookup finds the inherited function instead ofundefined. AMapdoesn't have this problem, andObject.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: $65andFood: $4. - Changing
"Clothes"to"clothes"incategoriesprintsFood: $6and thenclothes: $65.
