AI Hints
Home›JavaScript Tutorial›Practice: Arrays
JavaScript · Lesson 55 of 138

Practice: A Shopping Cart

Arrays in action.

⏱ 2 min read▶ Video at 1:07:15🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Practice: A Shopping Cart
From the video: Practice: A Shopping Cart
  • 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.

app.jsjavascript
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)}`);
Output
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.

keyvalue
pushadd items
filterremove one
map + reducethe total
Ternarythe 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
Next up: Practice: A Grade Report — sorting and summarizing