JS moving a variable that does not have to move

1

I've made a code that groups a few more items into one, by position x and y . The code is doing it correctly, but I'm having a problem. The first time the function executes, it does the whole process normally. When I click on a button to execute again, it should pick up the items from the PosicoesOriginal = [...] array and play on another variable for that variable to be modified and not the PosicoesOriginal ...

const PosicoesOriginal = [.....]; //Aqui tem todos os itens
function GeraPosicoesDistribuidores(){

       let grupos = [];

       //Aqui ele joga os itens dentro de outra variavel, pois não pode modificar o PosicoesOriginal

       let espelhoPosicoes = PosicoesOriginal;

       console.log(PosicoesOriginal);

       espelhoPosicoes.forEach(function(i, p){

        let toUp = i.y + distancia;
        let toDown = i.y - distancia;
        let toRight = i.x + distancia;
        let toLeft = i.x - distancia;
        let estado = i.estado;

          let gruposTemp = [];
          espelhoPosicoes.forEach(function(e, ps){

            if(between(e.y, toDown, toUp) && between(e.x, toLeft, toRight)){

              gruposTemp.push(e);
              espelhoPosicoes.splice(ps, 1);
            }
          });

          grupos.push(gruposTemp);
        });

        if(espelhoPosicoes != ''){

          espelhoPosicoes.forEach(function(e, p){
            let gruposTemp = [];

            gruposTemp.push(e);
            grupos.push(gruposTemp);
          });
        }

        console.log(PosicoesOriginal); //Verifico o que tem
        return grupos;
    }

In the first console.log it displays all the data correctly, in the last console.log it displays fewer items, but the strange thing is that I did not put% to move splice to PosicoesOriginal . If I remove the espelhoPosicoes it displays the same in the 2 console.log

    
asked by anonymous 23.03.2017 / 19:24

1 answer

0

PosicoesOriginal and espelhoPosicoes refer to the same object, that is, when espelhoPosicoes changes the object, the changes are reflected in PosicoesOriginal . If you need to change the value of one without changing the other value, you must copy the object. Since the object is an Array, you can copy it as follows:

    espelhoPosicoes = PosicoesOriginal.slice()

See the slice documentation at MDN

    
24.03.2017 / 15:28