0

I'm trying to delete object from array by title in this situation, but it doesnt work for me. Also, addItem work properly

addItem() {
    console.log(this.item.title + ' ' + this.item.quantity);
    this.ListOfUsedMaterials.push({ title: this.item.title, quantity: this.item.quantity});
    this.item.title = "";
    this.item.quantity = ""; 
}


//delete from array by title
deleteItem() {
    console.log("ID ARTIKLA: ", this.item.title);

    for (var i=0; i < this.ListOfUsedMaterials.length; i++) {
      if (this.ListOfUsedMaterials[i]["title"] == this.item.title) {
        this.ListOfUsedMaterials.splice(i, 1);
      }
    }

}

2 Answers 2

2

Just use filter :

deleteItemfromArray(title = this.item.title) {
  this.ListOfUsedMaterials = this.ListOfUsedMaterials
    .filter(item => item.title != title);
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can try like this. we need to iterate loop from the end because here we are deleting the array element, I hope it helps you out.

deleteItem() {
console.log("ID ARTIKLA: ", this.item.title);
var i = 0;
for (i; i < this.ListOfUsedMaterials.length - 1; --i) {
   if (this.ListOfUsedMaterials[i]["title"] == this.item.title) {
      this.ListOfUsedMaterials.splice(i, 1);
    }
  }
}

keep declaration i outside for loop because for loop tries to create new variable for every iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.