Delete selected data from array

Asked

Viewed 72 times

1

In my function I insert a data informed in an array and in a box for user viewing. But if he wants to remove this information, he selects it and is withdrawn through Function! But if he reports the same information again, it is the error stating that it already exists!

Ex:

variaveis na function
         w_Cont_Qtde = 1;
         w_Qtde_Peri = $arr_w_param[10]; --> $arr_w_param[10] é a quantidade informada em uma tela anterior (ex: 5 / 10 / ...) 
         v_patr = new Array (w_Qtde_Peri);

Inserts the data

function move(Origem, Destino)
{   
   var w_valor = Origem.value;  
 if (w_Cont_Qtde <=  w_Qtde_Peri)
    {        
    if ((v_patr.indexOf(w_valor) == -1) && (w_valor != ""))
       {
        var opt = document.createElement("option"); 
        opt.text = w_valor ;
        opt.value = w_valor ;
        Destino.options.add(opt);
        v_patr[w_Cont_Qtde]= w_valor;
        w_Cont_Qtde = w_Cont_Qtde +1;
        return true;
       }       
    else
        {   
        alert("Patrimônio OU Serial já existe OU não é válido!");
        return true;    
        }
   }
 alert("Quantidade informada ja Incluida !!!");
return true; 
}

Remove the data (you are only deleting from the box)

function tira(Destino) 
{
    var i;
    for(i = 0; i < Destino.options.length; i++)
    { 
        if (Destino.options[i].selected && Destino.options[i].value != "")
        {
            w_valor=Destino.options[i].value;
            w_Cont_Qtde = w_Cont_Qtde - 1;
            Destino.remove(Destino.selectedIndex);
        }
    }
}

My problem is: "Delete the selected data from the array as well, because from the box it already eliminates."

1 answer

4


you can remove items from a javascript array using the splice method, you inform in the first parameter the item index and in the second parameter the number of items to remove.


Edited (Example of Usage)

meuArray.splice(meuArray.indexOf(meuValor), 1);

i.e., it will take the index of the item to be removed from the array and will pass in the first parameter, and it will remove 1 item after this index (2nd parameter)

  • most preferably for the documentation of Mozilla dev https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

  • Thank you Willian, for future responses I will use the Mozilla documentation.

  • @dennis90 if it were to apply would be like?

Browser other questions tagged

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