joel
joel

Reputation: 43

Array manipulation with splice

i have this array two functions one adds to it the other one takes away from it or at least thats the plan. can someone look at my code and see whats wrong with my second function. splice is taking my last element on array but not the specific one that am trying to get. please

var shoppingCart = [];
function AddtoCart(name, description, price) {
  // JavaScript Object that  holds three properties :    Name,Description and Price
  var singleProduct = {};
  //Fill the product object with data
  singleProduct.Name = name;
  singleProduct.Description = description;
  singleProduct.Price = price;
  //Add newly created product to our shopping cart 
  shoppingCart.push(singleProduct);
  //call display function to show on screen

}

function removefromCart(name, description, price) {
  // JavaScript Object that will hold three properties :    Name,Description and Price
  var singleProduct = {};
  //Fill the product object with data
  singleProduct.Name = name;
  singleProduct.Description = description;
  singleProduct.Price = price;
  var index = shoppingCart.indexOf(singleProduct);
  shoppingCart.splice(index, 1);
}

Upvotes: 0

Views: 53

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Inside removefromCart, singleProduct is a newly created object, so it definitely won't exist in shoppingCart, even if it has the same properties - variables of nonprimitives (such as objects) essentially point to memory locations, so if you create a new object, the variable pointing to that object has a new memory location that nothing else in your script knows about, so anyArr.indexOf(newObject) will always return -1.

Use .findIndex instead:

function removefromCart(name, description, price) {
  const index = shoppingCart.findIndex(({ Name, Description, Price }) => (
    name === Name &&
    description === Description &&
    price === Price
  ));
  if (index === -1) {
    console.log('No matching product found!');
    return;
  }
  shoppingCart.splice(index, 1);
}

Upvotes: 3

Related Questions