Adding and removing elements in an array

3

I have the following structure:

var elementos = ["teste1","teste2","teste3","teste4","teste5","teste6","teste7","teste8","teste9","teste10","teste11","teste12"];
var elementosPossui = [];

function carregaTabelas() {
  carregaTabelaElementos();
  carregaTabelaElementosPossui();
  document.getElementById("conteudoArrays").innerHTML = '['+ elementos.toString()+']['+elementosPossui.toString()+']';
};

function carregaTabelaElementos() {
  var k = 0; var tabela = '<table>';
  for (var i = 0; i < 4; i++) {
    tabela += '<tr>';
    for (var j = 0; j < 3; j++) {
      if(typeof elementos[k] === "undefined"){
        tabela += '<td><span>[0]</span></td>';
        k++;
      }else{
        tabela += '<td><span id="'+elementos[k]+'" onclick="adicionar('+elementos[k]+')">['+elementos[k]+']</span></td>';
        k++;
      }            
    }
    tabela += '</tr>';
  }
  tabela += '</table>';
  document.getElementById("elementos").innerHTML=tabela;
};

function carregaTabelaElementosPossui() {
  var k = 0; var tabela = '<table>';
  for (var i = 0; i < 4; i++) {
    tabela += '<tr>';
    for (var j = 0; j < 3; j++) {
      if(typeof elementosPossui[k] === "undefined"){
        tabela += '<td><span>[0]</span></td>';
        k++;
      }else{
        tabela += '<td><span id="'+elementosPossui[k]+'" onclick="remover('+elementosPossui[k]+')">['+elementosPossui[k]+']</span></td>';
        k++;
      }
    }
    tabela += '</tr>';
  }
  tabela += '</table>';
  document.getElementById("elementosPossui").innerHTML=tabela;
};

adicionar = function(id) {
  log = document.getElementById("log");
  var index = elementos.lastIndexOf(id);
  elementosPossui.push(elementos.splice(index, 1));
  carregaTabelas();
  log.innerHTML = index;
};

remover = function(id) {
  log = document.getElementById("log");
  var index = elementosPossui.lastIndexOf(id);
  elementos.push(elementosPossui.splice(index, 1));
  carregaTabelas();
  log.innerHTML = index;
};

carregaTabelas();
Selecione um elemento: <div id="elementos"></div>
<br/><br/>
Elementos adicionados: <div id="elementosPossui"></div>
<br/><br/>
<div id="conteudoArrays"></div>
<br/><br/>
Log: <div id="log"></div>

I'm having trouble adding and removing the element that the user clicked on the array.

The idea is that when you select the element of the first table, it is added in the second, and when you select an element of the second, it is added in the first one, always adding the element to the end of the table.

I thought the combination of methods indexOf , splice and push this way:

index = indexOf(valorDoElemento);
array.push(array.splice(index, 1));

They would solve the problem, instead it simply does not find the element in the array.

    
asked by anonymous 04.08.2015 / 19:43

2 answers

2

To resolve you have to change the following points:

  • onclick () - Put your string in quotation marks.
  • splice () - Returns an array, in which case the element will always be in position [0] when removing and adding.
  • Follow the example below with the comments on the lines where the changes were made.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Exemplo utilizando socket.io</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />    
        <script type="text/javascript" src="js/js_1.9/jquery-1.8.2.js"></script>  
        <script type="text/javascript" src="js/js_1.9/jquery-ui-1.9.1.custom.min.js"></script>  
        
        <style type="text/css"> h2 { color: #439; font-size: 120%;} </style> 
    </head>
    <body>    
        Selecione um elemento: <div id="elementos"></div>
        <br/><br/>
        Elementos adicionados: <div id="elementosPossui"></div>
        <br/><br/>
        <div id="conteudoArrays"></div>
        <br/><br/>
        Log: <div id="log"></div>
    </body>
    <script type="text/javascript">
        var elementos = ["teste1","teste2","teste3","teste4","teste5","teste6","teste7","teste8","teste9","teste10","teste11","teste12"];
        var elementosPossui = [];
    
        function carregaTabelas() {
          carregaTabelaElementos();
          carregaTabelaElementosPossui();
          document.getElementById("conteudoArrays").innerHTML = '['+ elementos.toString()+']['+elementosPossui.toString()+']';
        };
    
        function carregaTabelaElementos() {
          var k = 0; var tabela = '<table>';
          for (var i = 0; i < 4; i++) {
            tabela += '<tr>';
            for (var j = 0; j < 3; j++) {
              if(typeof elementos[k] === "undefined"){
                tabela += '<td><span>[0]</span></td>';
                k++;
              }else{
                // NESSA LINHA A FUNCAO PASSA STRING ENTAO COLOCAR ENTRE ASPAS
                tabela += '<td><span id="'+elementos[k]+'" onclick="adicionar(\''+elementos[k]+'\')">['+elementos[k]+']</span></td>';
                k++;
              }            
            }
            tabela += '</tr>';
          }
          tabela += '</table>';
          document.getElementById("elementos").innerHTML=tabela;
        };
    
        function carregaTabelaElementosPossui() {
          var k = 0; var tabela = '<table>';
          for (var i = 0; i < 4; i++) {
            tabela += '<tr>';
            for (var j = 0; j < 3; j++) {
              if(typeof elementosPossui[k] === "undefined"){
                tabela += '<td><span>[0]</span></td>';
                k++;
              }else{
                // NESSA LINHA A FUNCAO PASSA STRING ENTAO COLOCAR ENTRE ASPAS
                tabela += '<td><span id="'+elementosPossui[k]+'" onclick="remover(\''+elementosPossui[k]+'\')">['+elementosPossui[k]+']</span></td>';
                k++;
              }
            }
            tabela += '</tr>';
          }
          tabela += '</table>';
          document.getElementById("elementosPossui").innerHTML=tabela;
        };
    
        adicionar = function(id) {
          log = document.getElementById("log");
          var index = elementos.lastIndexOf(id);
          var arr = elementos.splice(index, 1); // RETORNA UM ARRAY COM 1 ELEMENTO
          elementosPossui.push(arr[0]);
          carregaTabelas();
          log.innerHTML = index;
        };
    
        remover = function(id) {
          log = document.getElementById("log");
          var index = elementosPossui.lastIndexOf(id);
          var arr = elementosPossui.splice(index, 1); // RETORNA UM ARRAY COM 1 ELEMENTO
          elementos.push(arr[0]);
          carregaTabelas();
          log.innerHTML = index;
        };
    
        carregaTabelas();
    </script>  
    </html>
        
    04.08.2015 / 20:32
    2

    If you want, preserve the position, do it this way, I hope it's what you need:

    <html>
    <body onload="elementList();">
    
    </body>
    <script> 
      var elementos = ["teste1","teste2","teste3","teste4","teste5","teste6","teste7","teste8","teste9","teste10","teste11","teste12"];
       var arrayElementsAdds = [];
    function elementList() {
    
      var tableOne = 'Selecione o elemento:<br><table id="tabela_select"><tr>';
    
    for (var i in elementos) {
      tableOne += (i % 4 == 0) ? '</tr><tr>' : '';
      tableOne += '<td>[<span style="cursor:pointer;" onclick="addElement('+i+')" id="ele_select_'+i+'">'+elementos[i]+'</span>]</td>';
       }
    tableOne +='</tr></table>';
    
      var tableTwo = 'Elementos adicionados:<br><table id="tabela_select"><tr>';
    
    for (var i in elementos) {
      tableTwo += (i % 4 == 0) ? '</tr><tr>' : '';
      tableTwo += '<td>[<span style="cursor:pointer;" onclick="backElement('+i+')" id="ele_add_'+i+'">0</span>]</td>';
       }
    tableTwo +='</tr></table>';
    
    
    
    var html_array = 'var arrayElementsAdd = [';
    html_array +='<span id="col"></span>'; 
    html_array += ']';
    
    document.write(tableOne+tableTwo+html_array);
    
    }
    
    function removeValueToArray(arr) {
    
     var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
    
    }
    
    function addElement(pos) {
    
     var elem1 = document.getElementById('ele_select_'+pos);
     var elem2 = document.getElementById('ele_add_'+pos);
     var col = document.getElementById('col');
      if ( elem1.innerHTML != '0') {
     removeValueToArray(arrayElementsAdds, elem2.innerHTML);
     arrayElementsAdds.push(elem1.innerHTML);
     elem1.innerHTML = elem2.innerHTML;
     elem2.innerHTML = elementos[pos];
     col.innerHTML = arrayElementsAdds;
      }
    }
    
    function backElement(pos) {
    
     var elem1 = document.getElementById('ele_select_'+pos);
     var elem2 = document.getElementById('ele_add_'+pos);
     var col = document.getElementById('col');
    if ( elem2.innerHTML != '0') {
      removeValueToArray(arrayElementsAdds, elem2.innerHTML);
      elem1.innerHTML = elem2.innerHTML;
      elem2.innerHTML = '0';
      col.innerHTML = arrayElementsAdds;
    }
    }
    
    </script>
    </html>
        
    04.08.2015 / 21:54