1

I'm trying to remove specific element from a array in javascript, but, when I use the splice method, it deletes the whole array, instead of the specific element.

Code:

const cart = {
  contents: [],
  
  addItem(item) {
    cart.contents.push(item);
  },

  removeItem(item) {
    let searchItem = this.contents;

    if (searchItem.includes(item, 0)) {
      searchItem.splice(item);
      console.log(`${item} successfully removed from cart`);
    } else {
      console.log(`You tried to remove ${item} from your cart, but ${item} is not in the cart`);
    };
  }
};

cart.addItem("laptop");
cart.addItem("pen");
cart.addItem("book");

console.log("The cart contains:", cart.contents);
cart.removeItem("laptop");
console.log("The cart contains:", cart.contents);

the console log:

"The cart contains:" ["laptop", "pen", "book"] <br>
"laptop successfully removed from cart" <br>
"The cart contains:" []
adiga
  • 28,937
  • 7
  • 45
  • 66
RCross
  • 11
  • 1
  • 4
    update it to `searchItem.splice(item,1);` – Aalexander Feb 19 '21 at 17:42
  • By default it splices to the end of the array. You have to specify the length if you want it to remove fewer. – Barmar Feb 19 '21 at 17:43
  • `item` is a string. `splice` takes an index of the array as an argument. Not the element itself. You need to get the index first and then `splice` – adiga Feb 19 '21 at 17:45
  • @Aalexander `item` is the string OP is trying to remove – adiga Feb 19 '21 at 17:46
  • If you pass a non-number to `splice`, it will remove every item from the array. Weird. – adiga Feb 19 '21 at 17:55
  • thanks @adiga. I was able to fix by finding the index of the array as you said. ``` removeItem(item) { let searchItem = this.contents; if (searchItem.includes(item,0) ) { var a = searchItem.indexOf(item); searchItem.splice(1,a); console.log(`${item} successfully removed from cart` ); } else { console.log(`You tried to remove ${item} from your cart, but ${item} is not in the cart`); }; } ``` – RCross Feb 19 '21 at 17:58
  • The order of arguments to `splice` is wrong. It should be `searchItem.splice(a,1)` – adiga Feb 19 '21 at 18:00
  • Oh yes, you absolute right, I fixed, the order was wrong. Thanks for the tip on the includes. – RCross Feb 19 '21 at 18:03
  • Also, you don't need to search the array twice with `includes` and `indexOf`. Just get the index outside the if condition: `let index = searchItem.indexOf(item); if(index > -1) { // splice } else { // you tried to remove but doesn't exist}` – adiga Feb 19 '21 at 18:03
  • @adiga true instead of item it has to be the position of the element you like to remove – Aalexander Feb 19 '21 at 18:09

0 Answers0