How to delete a value from array if exist or push it to array if not exists?

Viewed 23930

How to delete a value from array if exist or push it to array if not exists?

HTML:

...
<button @click="addToOpenedMenuPosition(item.id)"
...

Vue.js:

data: function() { return {
    openedMenuPositionIds: [],
    ...
}
4 Answers

A simple implementation using js

const arr = ["one","two","three"]; //example array
const newId="one";                 //new id 

if(!arr.includes(newId)){          //checking weather array contain the id
    arr.push(newId);               //adding to array because value doesnt exists
}else{
    arr.splice(arr.indexOf(newId), 1);  //deleting
}
console.log(arr);

Assuming you want to remove item.id from the openedMenuPositionIds array which only contains ids as an integer, you can simply use array .indexOf(), .push() and .splice() methods to achieve this like:

var example2 = new Vue({
  el: '#example-2',
  data: function() {
    return {
      openedMenuPositionIds: [],
    }
  },
  // define methods under the `methods` object
  methods: {
  
    addToOpenedMenuPosition(id) {

      // Get the index of id in the array
      const index = this.openedMenuPositionIds.indexOf(id);
      if (index > -1) {
        // This means id is present in the array, so remove it
        this.openedMenuPositionIds.splice(index, 1);
      } else {
        // This means id is not present in the array, so add it
        this.openedMenuPositionIds.push(id);
      }
      
      // You can use this to debug purpose
      console.log( this.openedMenuPositionIds )
    }
  }
})

I assume the elements are unique so:

Its pretty simple. You can check with .includes() if its in the array and find the index of the id with .indexOf. Then you .splice() the element with the founded index, otherwise just push it into the array.

You need the return there to "stop" the function to continue:

addToOpenedMenuPosition(id){
   let arr = this.openedMenuPositionIds;
   if(arr.includes(id)){
      arr.splice(arr.indexOf(id), 1);
      return;
   }
   arr.push(id);
}

Create a new array by removing the item.id, but if item.id doesn't exit, then nothing will be removed and we can safely add item.id, otherwise we will return the modified array with removed item.id.

const newMenuPositionIds = menuPositionIds.filter(({id}) => id !== item.id);
if(newMenuPositionIds.length === menuPositionIds.length) {
    newMenuPositionIds.push(item.id);
}
return newMenuPositionIds;
Related