INNER CODE UNIT · JavaScript
itemIndex
maryamaljanabi/bestbags-nodejs-ecommerce · routes/index.js:50
const itemIndex = cart.items.findIndex((p) => p.productId == productId);
if (itemIndex > -1) {
// if product exists in the cart, update the quantity
cart.items[itemIndex].qty++;
cart.items[itemIndex].price = cart.items[itemIndex].qty * product.price;
cart.totalQty++;
cart.totalCost += product.price;
} else {
// if product does not exists in cart, find it in the db to retrieve its price and add new item
cart.items.push({
productId: productId,
qty: 1,
price: product.price,
title: product.title,
productCode: product.productCode,
});
cart.totalQty++;
cart.totalCost += product.price;