Skip to content

Instantly share code, notes, and snippets.

@jgdovin
Created June 17, 2015 20:20
Show Gist options
  • Save jgdovin/2cc63c2e36486113833f to your computer and use it in GitHub Desktop.
Save jgdovin/2cc63c2e36486113833f to your computer and use it in GitHub Desktop.
var shuffle = function (arr) {
//check to make sure we were not passed an empty value.
if (!arr) {
console.error('Target of shuffling cannot be empty.');
return false;
}
//check to make sure the value we were passed is an Array
if (arr.constructor != Array) {
console.error('Target of shuffling must be of type Array');
return false;
}
var result = [];
//as long as the array has a length keep running.
while (arr.length) {
//we will push a random number between 0 and the given array's length - 1 to account for
//arrays starting at 0. Splice returns an array so we will pop the element out of
//that array by pulling it out of the original array and pushing it to the result array.
//This technique is similar to the Fischer-Yates shuffling technique.
result.push(arr.splice(_.random(0, arr.length - 1), 1).pop())
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment