Start learning free

LESSON 190 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in JavaScript: Totals per Category with an Object

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 = ["Apple", "Bread", "Shirt", "Banana", "Pants"];
const prices = [2, 3, 25, 1, 40];
const categories = ["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 = ["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);

STEP 1 OF 10
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in JavaScript, explained

    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

    1. Create totals as an empty object with const. The loop will add keys to it.
    2. Loop over the positions. i runs from 0 while i < items.length, so the same index reaches all three arrays.
    3. Read the category of the current item into cat.
    4. Update the total. Set totals[cat] to its current value plus prices[i]. For a category seen for the first time, the current value is undefined, and || 0 replaces it with 0.
    5. Create lines, an empty array for the output rows.
    6. Get the sorted keys with Object.keys(totals).sort() and store them in keys.
    7. Loop over the keys with for (const cat of keys). This loop gives the categories themselves, not positions.
    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.
    10. Print result with console.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:

    iItemtotals afterwards
    0Apple{"Food":2}
    1Bread{"Food":5}
    2Shirt{"Food":5,"Clothes":25}
    3Banana{"Food":6,"Clothes":25}
    4Pants{"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] gives NaN the first time a category appears, because undefined + 2 is NaN.
    • Spelling differences. "Clothes" and "clothes" are different keys. With the last category changed to "clothes", the output has three lines: Clothes: $25, Food: $6 and clothes: $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 categories is shorter than prices, categories[i] is undefined, 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
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free