Adding and removing elements in an array

Asked

Viewed 493 times

4

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 from the array the element the user clicked on.

The idea is that when selecting the element from the first table, it is added in the second, and when selecting an element from the second, it is added in the first, always adding the element at the end of the table.

He believed that the combination of methods indexOf, splice and push thus:

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.

  • 1

    Please be more specific, Estou com problema para adicionar e remover o elemento do array que o usuário clicou. doesn’t help at all =)

  • But in your example you’re not taking the clicked element, you’re always taking the last.

  • Wouldn’t the missing declaration of variables? var add = Function... and var remove = Function...?

  • @gerep I was editing the question while you commented rs Not necessarily, I am adding the returned element at the index position coming from the index function

  • I don’t know if that’s clear enough...

  • @Ivanferrer no, that’s not it

  • I believe your problem lies in how to use the indexOf. Is missing the array =)

  • @Marcelobonifazio answered, and in the example I commented on the codes I changed, good luck there in the studies!

Show 3 more comments

2 answers

2


To solve you have to change the following points:

  1. onclick() - Place your string between quotes.
  2. splice() - Returns an array, in your case the element will always be at [0] when removing and adding.

Follow the example below with the comments in 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>

  • 1

    Ah, but it would be nice to already comment anyway right. ;) PS: de qualquer forma = antes do AP apresentar dúvidas, to help others with the same problem and tals...

  • 1

    rsrs, yes I ended up commenting, gets more didactic, thanks @gustavox

  • Then yes... :) +1

  • @Sneepsninja was exactly that, had never noticed that the splice method returned an array of elements that are inside the array

2

If you want to, preserve the position, do it this way, 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>

  • No @Ivanferrer, it would only be necessary to add the element in the other array and give a Sort in the array rs, but it was worth it anyway ^^

Browser other questions tagged

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