This code snippet can be use to Shuffle an array in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function shuffleArray ( array ) { var counter = array.length, temp, index; // While there are elements in the array while ( counter > 0 ) { // Pick a random index index = Math.floor( Math.random() * counter ); // Decrease counter by 1 counter--; // And swap the last element with it temp = array[ counter ]; array[ counter ] = array[ index ]; array[ index ] = temp; } return array; } var originalArray = [ 'a', 'b', 'c', 'd' ]; var shuffledArray = shuffleArray( originalArray ); |
working example : http://jsfiddle.net/grainier/J4BuD/