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

Asked

Viewed 1,300 times

1

I have a certain array:

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

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

seta_vender: function() {
    this.vender = !this.vender;
    if (this.vender) {
        this.acoes_selecionadas.push('Vender');
    } else {
        this.acoes_selecionadas.splice('Vender');
    }
}

3 answers

4


You can use Javascript Array indexof() Method to find the value index and remove the element from the list using splice (as mentioned in the question). In this example you can directly pass the index by v-for.

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>

0

Friend, I would use the function filter Javascript.

Giving a basic explanation, it interacts with its array, and when the imposed condition is true, it returns the element, already concatenating it back to the array. When it is false, the element is not retouched.

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

I hope I’ve helped.

Edit: Change in logic, as commented by Anderson.

  • 2

    I believe in case the condition would be reversed, vender !== val, because he wants to remove the element. Also, there is the question of whether there are duplicate elements. The filter will remove all, but maybe this is not what is desired - it would be good to question the AP on this.

0

Instead of searching for the index of the element with each click, you can use the v-for indexed:

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

It gets simpler, faster and more direct.

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>

<div id="app">
  <ul>
    <li v-for="(valor, index) in valores" @click="remove(index)">
      {{ valor }} ({{ index }})
    </li>
  </ul>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.