How do I treat a jQuery array (remove duplicates and prevent an item from appearing in 2 arrays)?

Asked

Viewed 105 times

4

I have 2 arrays (like and notlike) and as I give like or notlike, it adds the item in the array, currently it is like this:

//DEFINE ARRAYS
like = new Array();
notlike = new Array();

//SE CLICA NO btnlike VAI PARA ARRAY LIKE
$(".btnlike").on("click", function() {
    like.push($(this).attr('id'));
}

//SE CLICA NO btnnotlike VAI PARA ARRAY NOTLIKE
$(".btnnotlike").on("click", function() {
    notlike.push($(this).attr('id'));
}

Then I need to create 2 rules:

  1. The value cannot repeat inside the array, it must be unique
  2. Value cannot appear in 2 arrays if added in a array and then clicked the button to add to the other array, it should remove from the first array

2 answers

3

I’d do something like this, I hope it helps

//DEFINE ARRAYS
    like = new Array();
    notlike = new Array();
    opiniao = new Array(); //crie um novo array para guardar ambos

    $(".btn").on("click", function() { //coloque a mesma classe para os dois botões e separe "like" e "notlike" no atributo data-tipo; por exemplo data-tipo=like
    tipo = $(this).attr('data-tipo'); //aqui coletaremos se é like ou not-like


    if(tipo == 'like') { //se o tipo for like, entra aqui

    if(jQuery.inArray($(this).attr('id'), opiniao) !== -1) {    //vai checar se já tem no array opiniao, que está em ambos
    like.push($(this).attr('id'));
    opiniao.push($(this).attr('id')); //abastece opiniao também que é o verificador
    }
    }


    if(tipo == 'notlike') { //se o tipo for notlike, vem aqui
    if(jQuery.inArray($(this).attr('id'), opiniao) !== -1) {    //vai checar se já tem no array opiniao que tem em ambos
        notlike.push($(this).attr('id'));
        opiniao.push($(this).attr('id')); //abastece opiniao também que é o verificador
    }
    }

    });

1

Do not use id for the elements, because you will be duplicating id’s on both buttons, which is wrong in HTML. Instead use dataset data-id, for example:

<button class="btnlike" data-id="1">LIKE</button>
<button class="btnnotlike" data-id="1">NOT LIKE</button>

If using the tag button, as above, use value instead of data-id.

Use the method $.grep() jQuery to filter arrays by removing, if any, the value of the button clicked on the other array.

That is, you check whether the value exists in the array with .$inArray and then uses the $.grep to remove the value from the other array. The code is very simple, as shown below. You can even improve by joining the events in the two buttons in one, but I put them in separate even to make it easier to read.

//DEFINE ARRAYS
like = new Array();
notlike = new Array();

//SE CLICA NO btnlike VAI PARA ARRAY LIKE
$(".btnlike").on("click", function() {
   
   var valor = $(this).data("id");
   
   if(!~$.inArray(valor, like)){
      like.push(valor);
   }
   
   notlike = $.grep(notlike, function(v){
     return v != valor;
   });
   
   // daqui pra baixo é só para ilustração. Não inclua
   console.clear();
   console.log("LIKE: ", like.join(","));
   console.log("NOTE LIKE: ", notlike.join(","));
});

//SE CLICA NO btnnotlike VAI PARA ARRAY NOTLIKE
$(".btnnotlike").on("click", function() {

   var valor = $(this).data("id");
   
   if(!~$.inArray(valor, notlike)){ // verifica se já existe
      notlike.push(valor); // adiciona na array
   }
   
   like = $.grep(like, function(v){ // remove da outra array
     return v != valor;
   });

   // daqui pra baixo é só para ilustração. Não inclua
   console.clear();
   console.log("LIKE: ", like.join(","));
   console.log("NOTE LIKE: ", notlike.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1. <button class="btnlike" data-id="1">LIKE</button>
<button class="btnnotlike" data-id="1">NOT LIKE</button>
<br><br>
2. <button class="btnlike" data-id="2">LIKE</button>
<button class="btnnotlike" data-id="2">NOT LIKE</button>
<br><br>
3. <button class="btnlike" data-id="3">LIKE</button>
<button class="btnnotlike" data-id="3">NOT LIKE</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.