I need to do a function that reandomize all of the positions of an array.
Hi good morning, this is an easy way to do it:
function randomize(array){
var i,j,k;
for (i = array.length; i; i–) {
j = Math.floor(Math.random() * i);
k = array[i - 1];
array[i - 1] = array[j];
array[j] = k;
}
return array;
};
Let me know any question.
1 Like
Hello @DeveLop and @drektmr and welcome to the community
For whoever is wondering: This is called the Fisher–Yates shuffle.
Thanks for the example @drektmr. Due to using blockquotes the forum transformed your i--
into i–
which gives a syntax error.
This would be a ready to copy version of your function with modernized JS:
function randomize(arr){
let i, j;
for (i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
[arr[i - 1], arr[j]] = [arr[j], arr[i - 1]];
}
return arr;
}
It uses Destructuring to swap the variables.
I hope that helps!
Have a nice day both of you!
Michael
1 Like