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.

2
  • this.answers.contains = this.answers.contains.filter(element=> element !== answer) Commented Nov 17, 2021 at 7:55
  • refer here: stackoverflow.com/questions/43046332/… Commented Nov 17, 2021 at 7:55

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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.

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.