BeerBeard BeerBeard - 1 year ago 65
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,

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);
length -= 1;

return arr;

Answer Source

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:


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download