Practice: A Shopping Cart
Arrays in action.
Let's put arrays to work, with a small shopping cart. We'll add items, remove one, count the items, and work out the total with a discount. Every step uses something from this section.

- A small shopping cart
- Add, remove, count, total
- Everything from this section
The cart
The cart is an array of name and price pairs. Push adds items, and filter removes one, by keeping everything else. Map with destructuring pulls out the prices, and reduce adds them up. Finally, a ten percent discount applies if the total is over twenty. Run it.
let cart = [];
cart.push(["socks", 6], ["hat", 15], ["scarf", 12]);
cart = cart.filter(([name]) => name !== "hat");
cart.push(["gloves", 9]);
const names = cart.map(([name]) => name);
const total = cart.map(([, price]) => price).reduce((a, b) => a + b, 0);
const final = total > 20 ? total * 0.9 : total;
console.log("Items:", names.join(", "));
console.log("Count:", cart.length);
console.log(`Total: $${total}, after discount: $${final.toFixed(2)}`);Items: socks, scarf, gloves Count: 3 Total: $27, after discount: $24.30
What we used
Push to add, filter to remove without index juggling, map and reduce for the total, destructuring to unpack each pair, and a ternary for the discount. In the next section, we'll see that objects make this kind of data much clearer, with names instead of positions.
| key | value |
|---|---|
| push | add items |
| filter | remove one |
| map + reduce | the total |
| Ternary | the discount |
Summary
We built a shopping cart with push, filter, map, reduce, and destructuring. Next, another practice project, a grade report.
Key takeaways- Arrays of pairs
- filter to remove
- map + reduce to total