How can I delete an element of an array without knowing its index?

  • 0
    Hello.
    There is 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 element of the array using the .splice (index, 1);
    method My question is this: when the button is clicked, the selected element of the array, I completely assign it to the active variable. Already based on this information, can you 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, can we say "vue, find active inside arr and remove it"?
    Vue.js Rose Ballard, Jul 11, 2020

  • 2 Answers
  • 0
    If I understood everything correctly, then:

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




    and you don't need parentheses here for remove (). That is, just remove

    <button @click="remove()">Remove active button</button>
    Anonymous

  • 0
    How can you not know its index?



    v-for = "(button, index) in arr" and the index immediately appeared



    @ click = "remove (index)"



    And you don't need to come up with strange solutions.

    But if you need solutions that are not clear, then based on active you can make an array filter by the property in active



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


    Well, or some other property that can be active. You get the point
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!