Created
December 11, 2013 09:44
-
-
Save argshook/7907666 to your computer and use it in GitHub Desktop.
Two ways of shuffling arrays in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a simple and efficient way to shuffle | |
// a relatively small array. Doesn't work well | |
// with a lot of indices. See: http://stackoverflow.com/a/18650169/2104866 | |
var numbers = [1,2,3,4,5,6]; | |
numbers.sort(function() { | |
return .5 - Math.random(); | |
}); | |
// much more clever way to randomize an array | |
// using Fisher-Yates shuffle algorithm. | |
Array.prototype.shuffle = function() { | |
var i = this.length, j, temp; | |
if ( i == 0 ) return this; | |
while ( --i ) { | |
j = Math.floor( Math.random() * ( i + 1 ) ); | |
temp = this[i]; | |
this[i] = this[j]; | |
this[j] = temp; | |
} | |
return this; | |
} | |
// if, for some reason, you can't use prototype, | |
// here's the same Fisher-Yates algorithm as a function | |
function shuffleArray(array) { | |
for (var i = array.length - 1; i > 0; i--) { | |
var j = Math.floor(Math.random() * (i + 1)); | |
var temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment