0

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?

5

1 Answer 1

2

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.