Modermo Modermo - 1 month ago 6
Javascript Question

How do I delete from multiple arrays?

Say I have two arrays sitting inside an object, and a function to delete an item from an array specified by the user.

var warehouse{
shirts: [],
shorts: [],

deleteItem: function(itemType, itemNumber){
this.itemType.splice(itemNumber, 1);
}
}


So, if I do something like:

function('shirts', 0);


It should delete the first item in the 'shirts' array. Problem is, it is telling me that itemType is coming up as
undefined

Answer

You should use bracket notation:

var warehouse = {
  shirts: [1, 2, 3, 4],
  shorts: [1, 2, 3, 4],
  deleteItem: function(itemType, itemNumber){
    this[itemType].splice(itemNumber, 1);
  }
};

warehouse.deleteItem("shirts", 0);
console.log(warehouse);