Created
October 13, 2015 10:16
-
-
Save paveleremin/f3ad1f6ec22447e8ce47 to your computer and use it in GitHub Desktop.
Array shuffle, without creating new array
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
var array = [1, 2, 3, 4, 5, 6]; | |
Array.prototype.shuffle = function() { | |
var i = this.length, | |
tmp, | |
randIndex; | |
while (--i) { | |
randIndex = Math.floor(i * Math.random()); | |
tmp = this[i]; | |
this[i] = this[randIndex]; | |
this[randIndex] = tmp; | |
// or you can swap variables | |
// this[i] = [this[randIndex], this[randIndex] = this[i]][0] | |
} | |
return this; | |
} | |
array.shuffle(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment