I'm working on a Javascript exercise that requires a function that can search for an object with a certain property within an array. If such an object exists, the function should delete that object, then return the array. If no such object exists within the array, the function should return a string saying the object does not exist.
So far I have written the code below, taking the example of a shopping cart, but I'm not getting the desired result. If I search for the object at cart[0], it works as intended. However, anything with an index above 0 returns "That item is not in your cart." What am I doing wrong?
var cart = [{apples: 12}, {oranges: 20}, {grapes: 35}, {peaches: 18}]
function removeFromCart(item){
for (var i = 0; i < cart.length; i++){
if (cart[i].hasOwnProperty(item)) {
cart.splice(i, 1);
return cart;
}
else {
return "That item is not in your cart.";
}
}
}
cart.