What data structure is best for a shopping cart in JavaScript?
An object with item ID as key and quantity as value: { itemId: quantity }. This gives O(1) lookup, add, and remove. Alternatively, an array of { id, quantity } objects, but the object is simpler for this use case.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Food Ordering App: Cart Implementation in JavaScript
Use an object mapping item ID to quantity: cart = { 1: 2, 3: 1 }. addToCart increments, removeFromCart deletes, changeQuantity adjusts and removes at 0. Calculate total by summing price * qty for each item.
When decrementing, check if the quantity drops to 0 or below. If so, delete the item from the cart: if (cart[id] <= 0) delete cart[id]. This keeps the cart clean and the total accurate.
Sum price * quantity for each item: Object.entries(cart).reduce((sum, [id, qty]) => { const item = menu.find(m => m.id === parseInt(id)); return sum + item.price * qty; }, 0).
Still have questions?
Browse all our FAQs or reach out to our support team
