Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Created January 30, 2016 08:50
Show Gist options
  • Save stefanfrede/6476a9936067478d0f6a to your computer and use it in GitHub Desktop.
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.
/**
* 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