Luke Schunk
Luke Schunk

Reputation: 241

Shuffle Array function yields same result

This is a down and dirty vanilla javascript question. I'm using a classic array shuffle function:

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    while (0 !== currentIndex) {

      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

And then calling it repeatedly in another function:

  function generateQuartile (array) {

    var shuffle1 = shuffle(array);

    var shuffle2 = shuffle(array);

    var shuffle3 = shuffle(array);

    //all three shuffles are the same 

  }

The problem is, all three of those variables are yielding the same result. The array is shuffled once, and then not again. I can't seem to pin down what this is. I'm guessing it's some sort of scoping/hoisting problem but I really can't figure it out. Thanks for any help!

Upvotes: 0

Views: 196

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234807

The shuffling is working correctly. The problem is that you're returning the same array each time. At each call, you need to make a new array with the randomized elements. The easiest thing would be to clone the array right at the start of the function:

array = array.slice();

With that change, shuffle1, shuffle2, and shuffle3 will be three distinct arrays. Also, the original array will not be modified; that may be either a good or bad thing, depending on your design.

Alternatively, you can leave your shuffle function alone and clone each return value:

var shuffle1 = shuffle(array).slice();
// etc.

Upvotes: 2

Related Questions