BeerBeard BeerBeard - 4 months ago 11
Javascript Question

What is wrong with my shuffling program?

I wrote a shuffling program below and ran it through "Will It Shuffle?". The results appear to show that it's working in the console; it's shuffling the array. But the website shows me an all red box, making me think something is wrong with it.

function shuffle (array) {
var arr = [],
length = array.length,
el;

while (length > 0) {
var randomEl = Math.floor(Math.random() * (length - 0) - 0);
if (length > 1) {
el = array.splice(randomEl,1);
} else {
el = array.splice(0,1);
}
arr.push(el[0]);
length -= 1;
}

return arr;
}

Answer

That page ignores the returned value of the function, because it expects an in-place sort.

If you add this at the end of your code, it works as expected:

array.push(...arr);

You can also do it in-place directly:

function shuffle (array) {
  var length = array.length;
  while (length) {
    var randomEl = Math.floor(Math.random() * length);
    var el = array.splice(randomEl, 1);
    array.push(el[0]);
    --length;
  }
}
Comments