user3413170
user3413170

Reputation: 261

Taking one array and randomizing it into another array

I have two arrays (representing a deck of cards), one filled with the values 1-52, and another filled with nothing. I want to take the position randomly from the first array and take that object and put it into the next spot available in the randomized array. I have this so far:

var shufdeck = new Array();
while(sufdeck.length < 52)
{
    i = Math.floor(Math.random()*52);
    //shufdeck[0] = deck[i] etc.
}

I'm not sure if I should be using splice or something else to take it out of the first array and put it into the second. If possible shufdeck[] should be filled and deck[] would be empty.

How can I shuffle an array?

Upvotes: 0

Views: 58

Answers (1)

RobG
RobG

Reputation: 147523

Yes, you should splice out the chosen card, so:

var shuffledDeck = [];

while (deck.length) {
  shuffledDeck.push(deck.splice(Math.random()*deck.length | 0, 1)[0]);
}

or to be a little more efficient:

var i = deck.length;
while (i) {
  shuffledDeck.push(deck.splice(Math.random()*i-- | 0, 1)[0]);
}

Note that this will destroy deck. If you don't want that, copy it first:

var deckToShuffle = deck.slice();

Upvotes: 2

Related Questions