Home > Enterprise >  Adding and removing an element in an array
Adding and removing an element in an array

Time:12-24

There are 2 toggle buttons. If the value is true, then add to the array, otherwise remove the element.

data:

originality: []

toggles:

<toggle id='1' ref='toggleOriginal'> Click </toggle>
<toggle id='2' ref='toggleAnalog'> Click </toggle>

methods:

 if(this.$refs.toggleOriginal.isActive) {
    this.originality.push(this.$refs.toggleOriginal.id);
 } else {
    this.originality = this.originality.filter((item) => {
      return item == this.$refs.toggleOriginal.id;
   });
 }

 if(this.$refs.toggleAnalog.isActive) {
    this.originality.push(this.$refs.toggleAnalog.id);
  } else {
    this.originality = this.originality.filter((item) => {
      return item == this.$refs.toggleAnalog.id;
    });
  }

And the same for the second. In isActive I check for true / false. the problem is that if two toggle is true and I want to convert one to false, then the wrong element is removed. Perhaps you should use a different functionality?

CodePudding user response:

To remove from array using filter, you should test for non-equality. Your example uses equality, and that will remove all but your item.

this.originality = this.originality.filter((item) => {
      return item !== this.$refs.toggleOriginal.id;
   });

or splice

const index = this.originality.indexOf(this.$refs.toggleOriginal.id)
this.originality.splice(index, 1)
  • Related