You can look at the project for context.
//Global
//Variables
let inventory = [{name: "banana", quantity: 4}, {name: "chin", quantity: 6}, {name: "yelb", quantity: 10}];
//Functions
function findProductIndex (item) {
item = item.toLowerCase();
for (let i = 0; i < inventory.length; i++) {
if (inventory[i].name == item) {
return i;
} else if (i == inventory.length - 1) {
return -1;
}
}
}
function addProduct (product) {
if (findProductIndex(product.name) == -1) {
inventory.push(product);
console.log(`${product.name} added to inventory`);
} else {
inventory[findProductIndex(product.name)].quantity += product.quantity;
console.log(`${product.name} quantity updated`);
}
}
function removeProduct (name, quantity) {
if (findProductIndex(name) == -1) {
console.log(`${name} not found`);
} else if (quantity > inventory[findProductIndex(name)].quantity) {
console.log(`Not enough ${name} available, remaining pieces: ${inventory[findProductIndex(name)].quantity}`);
} else {
inventory[findProductIndex(name)].quantity -= quantity;
console.log(`Remaining ${name} pieces: ${inventory[findProductIndex(name)].quantity}`);
if (inventory[findProductIndex(name)].quantity == 0) {
inventory.splice(inventory[findProductIndex(name)], 1);
console.log("This is running");
}
}
}
I have tried to use the splice function to remove the product in the removeProduct function to remove products but when I call it, it removes the first element in the array, banana.
Here is how I am calling it and checking the array:
removeProduct("yelb", 10);
console.log(inventory);