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: [],
...
}
Show activity on this post. Show activity on this post. 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 .
To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
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);
}
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 )
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With