1

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.

Max
  • 11
  • 3
  • this.answers.contains = this.answers.contains.filter(element=> element !== answer) – Erenn Nov 17 '21 at 07:55
  • refer here: https://stackoverflow.com/questions/43046332/how-to-remove-an-item-from-an-array-in-vue-js – gretal Nov 17 '21 at 07:55

2 Answers2

1

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!

B0BBY
  • 1,012
  • 6
  • 24
1

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.

gengar.value
  • 198
  • 3