Problem overview
Each product has a price and a category. The program must add up the prices for each category and print one line per category, sorted by category name. The data lives in three parallel arrays: items, prices and categories.
With prices = [2, 3, 25, 1, 40] and categories = ["Food", "Food", "Clothes", "Food", "Clothes"], the Food items cost 2 + 3 + 1 = 6 and the Clothes items cost 25 + 40 = 65. The output is:
Clothes: $65
Food: $6
Clothes comes first, because the lines are sorted alphabetically.
Approach: accumulate in an object, then sort the keys
The categories are not known in advance and can arrive in any order, so the program uses an object, totals, as a set of running totals with one key per category. The loop visits each item and adds its price to the entry of its category. An unseen category has no entry yet, so its total starts from 0.
An object can't be sorted, but its keys can: Object.keys(totals) returns them as an array, and sort() orders that array. A second loop then walks the sorted keys and builds one line each. Separating the counting from the printing keeps both loops simple.
The object matters because of lookup speed and simplicity. Keeping a list of category names and searching it for every item would mean scanning the list each time. With an object, totals[cat] goes straight to the right entry, and the "have I seen this category?" question is answered by the default of 0. The previous version used an object as a lookup table for reading; this one also writes to it.
Step by step
- Create
totalsas an empty object withconst. The loop will add keys to it. - Loop over the positions.
iruns from 0 whilei < items.length, so the same index reaches all three arrays. - Read the category of the current item into
cat. - Update the total. Set
totals[cat]to its current value plusprices[i]. For a category seen for the first time, the current value isundefined, and|| 0replaces it with 0. - Create
lines, an empty array for the output rows. - Get the sorted keys with
Object.keys(totals).sort()and store them inkeys. - Loop over the keys with
for (const cat of keys). This loop gives the categories themselves, not positions. - Push one row per category: the name, a colon and space, a dollar sign and the total.
- Join the rows with
"\n"intoresult. - Print
resultwithconsole.log.
The solution in JavaScript
const items = ["Apple", "Bread", "Shirt", "Banana", "Pants"];
const prices = [2, 3, 25, 1, 40];
const categories = ["Food", "Food", "Clothes", "Food", "Clothes"];
const totals = {};
for (let i = 0; i < items.length; i++) {
const cat = categories[i];
totals[cat] = (totals[cat] || 0) + prices[i];
}
const lines = [];
const keys = Object.keys(totals).sort();
for (const cat of keys) {
lines.push(cat + ": $" + totals[cat]);
}
const result = lines.join("\n");
console.log(result);
How totals grows
This is the object after each pass of the first loop:
| i | Item | totals afterwards |
|---|---|---|
| 0 | Apple | {"Food":2} |
| 1 | Bread | {"Food":5} |
| 2 | Shirt | {"Food":5,"Clothes":25} |
| 3 | Banana | {"Food":6,"Clothes":25} |
| 4 | Pants | {"Food":6,"Clothes":65} |
At the end, Object.keys(totals) is ["Food", "Clothes"], the order the categories first appeared. After .sort() it is ["Clothes", "Food"], which is the order of the output.
Details worth knowing
The expression (totals[cat] || 0) + prices[i] relies on undefined being falsy: || returns its left side when that is truthy and its right side otherwise. A stored total of 0 would also be replaced by 0, which is harmless here because the replacement is the same number. Newer code often writes ??, which replaces only undefined and null.
The parentheses matter. Without them, totals[cat] || 0 + prices[i] parses as totals[cat] || (0 + prices[i]), since + binds tighter than ||. That would assign just the price whenever a total exists, and lose the earlier sum.
With no comparator, sort() converts the elements to strings and compares them by UTF-16 code units. For category names that means capitals sort before lowercase letters: ["Food", "apple", "Clothes"] sorts to ["Clothes", "Food", "apple"]. The lesson's names all start with a capital, so plain sort() is right. For mixed case, pass a comparator such as (a, b) => a.localeCompare(b).
Object keys keep a defined order too: integer-like keys come first in ascending order, then the other keys in insertion order. Relying on that would give Food before Clothes here, which is exactly why the program sorts the keys explicitly.
Complexity
Let n be the number of items and k the number of distinct categories. The first loop is O(n), since each object update takes constant time on average. Sorting the keys costs O(k log k) and building the rows is O(k). The total is O(n + k log k), and the extra space is O(k).
Edge cases and common mistakes
- Skipping the default.
totals[cat] + prices[i]givesNaNthe first time a category appears, becauseundefined + 2isNaN. - Spelling differences.
"Clothes"and"clothes"are different keys. With the last category changed to"clothes", the output has three lines:Clothes: $25,Food: $6andclothes: $40. - Looping over the object in insertion order. The rows would follow the order the categories first appeared, not alphabetical order.
- Arrays of different lengths. If
categoriesis shorter thanprices,categories[i]isundefined, and JavaScript turns that into the key"undefined". The extra prices end up in a category with that odd name. - One item only. A single item gives a single line and no newline.
Testing
A cart with one item, items = ["Tea"], prices = [5] and categories = ["Drinks"], prints:
Drinks: $5
With the last category in the lesson's data changed to "clothes", it prints:
Clothes: $25
Food: $6
clothes: $40
