Home » vue » Using splice() to remove items that matches condition from array

Using splice() to remove items that matches condition from array

Posted by: admin November 26, 2021 Leave a comment

Questions:

Im trying to via a for-loop remove all the items that matches a condition in the state array. But it seems to only be removing the last items in the array and not the ones that matches. Am I using the .splice() incorrectly? Thanks in advance. Code is:

rmTravel() {
           for(var i = 0; i < this.cards.length; i++){
               if(this.cards[i].sg_categories.includes("travel")){
                   this.cards.splice(i, 1);
                   console.log('Removed following card:', this.cards[i].slug)
               }
           }
           console.log('Cards in cards state: ', this.cards)
       }
Answers:

This is a bit of a classic problem; you’re iterating forward and shrinking the array at the same time so you’re going to end up skipping over records.

I suggest using Array.prototype.filter() instead

this.cards = this.cards.filter(({ sg_categories }) => 
    !sg_categories.includes('travel'))

This will reduce the array to entries who’s sg_categories property does not include “travel”.