R
R
r_g_b_a2020-11-18 17:22:59
Vue.js
r_g_b_a, 2020-11-18 17:22:59

How to remove an element from an array without knowing its index?

Hello.
There is such an example:

<div id="app">
  <button v-for="button in arr" @click="active = button">{{button}}</button>
  <button @click="remove()">Remove active button</button>
</div>

new Vue({
  el: "#app",
  data: {
  	active: null,
    arr: ['a', 'b', 'c']
  },
  methods: {
    remove() {
      
    }
  }
})

Clicking on "Remove active button" should remove the active button.
I know that you can get the index in the v-for loop, and then remove the desired array element using the .splice(index, 1);
My question is this: when the button is clicked, I fully assign the selected element of the array to the variable active . Already on the basis of this information, you can determine the position of the data in the array?
Or maybe there is another way to remove without having to use index and .splice() ?
In other words, is it possible to say "vue, find the active inside arr and remove it"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim, 2020-11-18
@r_g_b_a

If I understand correctly, then:

remove() {
  this.arr = this.arr.filter( button => button !== this.active)
}

and you don't need parentheses in remove(). That is justremove
<button @click="remove()">Remove active button</button>

D
Dima Pautov, 2020-11-18
@bootd

How do you not know his index?
v-for="(button, index) in arr" and the index immediately appeared
@click="remove(index)"
No need to come up with weird solutions.
But if you need incomprehensible solutions, then based on active, you can make an array filter by the property located in active

computed: {
  newArray () {
    return this.arr.filter(item => item.id === this.active.id)
  }
}

Well, or some other property that may be in active. You get the gist

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question