Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or remove element in array

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");
    }
}
like image 318
DionysoSong Avatar asked Nov 27 '22 20:11

DionysoSong


2 Answers

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
  }
}
like image 174
onmyway133 Avatar answered Nov 30 '22 08:11

onmyway133


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

like image 33
Non404 Avatar answered Nov 30 '22 09:11

Non404