Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript + Vue error: array.filter not working as expected

I have two arrays:

  • $globalData.dishes defined in main.js as ['Salad', 'Burger', 'Cake'].
  • dishes defined in App.vue as an empty array.

The code I’ve written should list all dishes in $globalData.dishes originally in pink. When a dish is clicked, it is added to dishes and its color changes to green (this works). When clicked on again it is removed from dishes and its color reverts back to pink (this does not work).


App.vue:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<template>
  <div>
    <h2>Dishes:</h2>
    <ul>
      <li v-for="dish in this.$globalData.dishes" v-bind:key="dish.id"
      :style="[dishes.includes(dish) ? 
      {'background-color': 'lightgreen'} :
      {'background-color': 'pink'}]"
      @click="addDish(dish)">
      {{ dish }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data () {
    return {
      dishes: []
    }
  },
  methods: {
    addDish(dish){
      if (this.dishes.includes(dish)){
        this.dishes.filter((d) => d !== dish)
      } else {
        this.dishes.push(dish);
      }
    },
  }
}
</script> 

main.js:

...
Vue.prototype.$globalData = Vue.observable({
  dishes: ['Salad', 'Burger', 'Cake'],
});
...

>Solution :

It looks like the issue is with the addDish method in your App.vue component.

The Array.filter method doesn’t modify the original array, it creates a new array. Therefore, when you try to remove a dish by using this.dishes.filter() method, it creates a new array, but you are not assigning it back to this.dishes.

You need to update your addDish method to correctly remove the dish from the array.

methods: {
    addDish(dish){
      if (this.dishes.includes(dish)){
        this.dishes = this.dishes.filter((d) => d !== dish);
      } else {
        this.dishes.push(dish);
      }
    },
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading