Home > other >  How to delete items from an array in Vue
How to delete items from an array in Vue

Time:11-17

I have a function called updateAnswer with multiple dynamic parameters.

        updateAnswer(key, answer, array = false) {
        if (array) {
            if(this.answers.contains.find(element => element === answer)) {

                //Delete item from array if already element already exists in this.answers.contains array.

            } else {
                Vue.set(this.answers, key, [...this.answers.contains, answer]);
            }

        } else {
            Vue.set(this.answers, key, answer);
        }
    },

I'd like to know how delete an item in the array if the value already exists in the array.

CodePudding user response:

You can use method called splice:

Just reference on your array and set values in the brackets the first is referenced on the position, the second is how many datas you want to splice/delete.

The function looks like this:

this.array.splice(value, value)

Lets see on an example - you have array food= [apple, banana, strawberry] than I'm using this.food.splice(1,1)..

my array looks now like this food = [apple, strawberry] - first value in my brackets are the position, the second one is the amount of "numbers" you want to delete.

Hopefully this helps you out!

CodePudding user response:

I suppose each value in this.answers.contains is unique?

Anyways, if you just want to delete the item if already exists, I suggest filter(). It should look like below:

if(this.answers.contains.find(element => element === answer)) {
    this.answers.contains = this.answers.contains.filter(c => c !== answer)
}

Also, the if condition if(this.answers.contains.find(element => element === answer)) could also be replaced by if(this.answers.contains.includes(answer))

Hope that could help you.

  • Related