guillaume kotarba guillaume kotarba - 3 months ago 8
Javascript Question

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");
}
}

Answer

you are wrongly checking the duplication, by just comparing every items with pseudo. you need to loop through all the items to see if it matches any, then perform add/remove based on matching. following code will work for you.

function checkAmi(pseudo, id) {
    var info = ({
        pseudo: pseudo,
        id: id
    });
    var getIndexOf = function (psdu) {
        for (var i = 0; i < amisNotifies.length; i++) {
            if (amisNotifies[i].pseudo === psdu) {
                return i;
            }
        }

        return -1;
    };

    if (amisNotifies.length > 0) {
        var index = getIndexOf(pseudo);
        if (index > -1) {
            //so already exists. now remove it.
            Array.prototype.splice.call(amisNotifies, index, 1);
            $("#checkAmi" + id).addClass("fa-circle-o");
            $("#checkAmi" + id).removeClass("fa-check-circle-o");
        }
        else {
            //does not exist, now add it
            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");
    }
}
Comments