How to remove item from an array by filtering by value?

1

I have a certain array:

acoes_selecionadas: ['nome1', 'nome2'];

I'm using this function, but splice works based on element ID, I need to find a way to remove it by value.

seta_vender: function() {
    this.vender = !this.vender;
    if (this.vender) {
        this.acoes_selecionadas.push('Vender');
    } else {
        this.acoes_selecionadas.splice('Vender');
    }
}
    
asked by anonymous 14.12.2018 / 04:39

3 answers

3

You can use JavaScript Array indexOf () Method to find the index of the value and remove the element from the list using splice (as mentioned in the question). In this example you can directly pass the index by passing% in%.

new Vue({
  el: '#app',
  data: {
    acoes_selecionadas: ['nome1', 'nome2']
  },
  methods: {
    seta_vender(valor) {
      var indice = this.acoes_selecionadas.indexOf(valor)
      this.acoes_selecionadas.splice(indice , 1)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
  <div id='app'>
    <ul>
      <li v-for='valor in acoes_selecionadas' @click='seta_vender(valor)'>
        {{valor}}
      </li>
    </ul>
  </div>
    
14.12.2018 / 11:32
0

Friend, I would use the javaScript filter function .

By giving a basic explanation, it interacts with its array, and when the imposed condition is true, it returns the element, already concatenating it back into the array. When false, the element is not retuned.

seta_vender : acoes_selecionadas.filter((val) => {
   return vender != val;
});

I hope I have helped.

Edit: Change in logic, as commented by Anderson.

    
14.12.2018 / 10:34
0

Instead of looking at the index of the element with each click, you can use v-for with indexes:

<li v-for="(valor, index) in valores" @click="remove(i)">

It's simpler, faster and more straightforward.

new Vue({
  el: "#app",
  data: {
    valores: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
  },
  methods: {
    remove: function(i) {
      this.valores.splice(i, 1)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><divid="app">
  <ul>
    <li v-for="(valor, index) in valores" @click="remove(index)">
      {{ valor }} ({{ index }})
    </li>
  </ul>
</div>
    
14.12.2018 / 12:46