I'd like to add an object to an array if it does not already exists and delete it if it already exists in the array. I succeed for adding the first item, but it does not work if I add an other object in the array. I can delete the first item. There is a bug, i don't know why.
Here is my code :
function checkAmi(pseudo, id) {
var info = ({
pseudo: pseudo,
id: id
});
if (amisNotifies.length > 0) {
// iterate over each element in the array
for (var i = 0; i < amisNotifies.length; i++) {
console.log(angular.toJson(amisNotifies[i].pseudo));
// look for the entry with a matching `code` value
if (amisNotifies[i].pseudo === pseudo) {
amisNotifies.removeValue('pseudo', pseudo);
$("#checkAmi" + id).addClass("fa-circle-o");
$("#checkAmi" + id).removeClass("fa-check-circle-o");
} else {
amisNotifies.push(info);
$("#checkAmi" + id).removeClass("fa-circle-o");
$("#checkAmi" + id).addClass("fa-check-circle-o");
}
}
} else {
amisNotifies.push(info);
$("#checkAmi" + id).removeClass("fa-circle-o");
$("#checkAmi" + id).addClass("fa-check-circle-o");
}
}
You can do this
const addOrRemove = (array, item) => {
const exists = array.includes(item)
if (exists) {
return array.filter((c) => { return c !== item })
} else {
const result = array
result.push(item)
return result
}
}
TESTED
this is another simple solution:
var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];
array.indexOf(newItem) === -1 ? array.push(newItem) : array.splice(array.indexOf(newItem), 1);
console.log(array)
indexOf will return -1 if it's not found, meaning that if it doesn't exist, you will add.. for more Info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
else if it is found, meaning that it exists, you will delete it with splice, the first parameter is the index and the second is how many elements you will delete: for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
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