Created
January 30, 2016 08:50
-
-
Save stefanfrede/6476a9936067478d0f6a to your computer and use it in GitHub Desktop.
This snippet here uses Fisher-Yates Shuffling Algorithm (https://www.wikiwand.com/en/Fisher–Yates_shuffle) to shuffle a given 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
/** | |
* Example: | |
* var a = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; | |
* var b = shuffleArray( a ); | |
* console.log(b); | |
* // [2, 7, 8, 6, 5, 3, 1, 4] | |
*/ | |
function shuffleArray( arr ) { | |
var i, | |
j, | |
temp; | |
for (i = arr.length - 1; i > 0; i--) { | |
j = Math.floor(Math.random() * (i + 1)); | |
temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
return arr; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment