Skip to content

Instantly share code, notes, and snippets.

@paulodiovani
Created February 26, 2014 12:01
Show Gist options
  • Save paulodiovani/9228333 to your computer and use it in GitHub Desktop.
Save paulodiovani/9228333 to your computer and use it in GitHub Desktop.
Returns a slightly reandomized version os an array.
(function() {
'use strict';
function shuffle(array) {
array.sort(function() {
return Math.floor( Math.random() * 3) -1;
});
return array;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
console.log( shuffle(arr) );
})();
@paulodiovani
Copy link
Author

The trick here is use Array.sort() method with a function that returns a random sort index (-1 | 0 | 1), so the array elements will be randomly swapped back or forward.

You can call it several times to generate more entropy:

console.log( shuffle( shuffle( shuffle( shuffle( arr )))) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment