Created
February 26, 2014 12:01
-
-
Save paulodiovani/9228333 to your computer and use it in GitHub Desktop.
Returns a slightly reandomized version os an 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
(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) ); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: