I have problems changing the position of an array element, without repeating any element

0
var palos = ['P','T','C','D'];
var palos2= palos;
var almacenInicial1 = palos[elecion];
var almacenInicial2 = palos[elecion2];

for(var i= 0;i<10;i++){

var elecion = Math.floor(Math.random()*palos.length);
var elecion2 = Math.floor(Math.random()*palos.length);

palos2[elecion2]= palos2[elecion];
palos2[elecion]=palos2[elecion2];
}

I am creating a program which allows me to shuffle the elements of the array, the objective is for the program to change positions 'without repeating any element'. But the elements are repeated to me. And investigated and what I could understand is that I must store two random positions and store each one individually, then change the position 1 for the two and vice versa and thus should not repeat any element. But only the elements are repeated, and I can not manage to change the elements without being repeated, Gelp me, Please !!

    
asked by EHdeze 21.10.2017 в 03:40
source

1 answer

0

Do not get too involved, you can use sort :

var palos = ['P','T','C','D'];
var palos2 = palos.slice().sort(function(a, b){return 0.5 - Math.random()});
                // ^^^^ .slice() para crear una copia del array original y no hacerle sort

Using slice we create a copy of the array palos and then do the sorting, this if you do not want to modify the array palos , even if this does not matter you can apply the method sort directly to palos .

var palos = ['P','T','C','D'].sort(function(a, b) {return 0.5 - Math.random()});
    
answered by 21.10.2017 / 05:07
source