-
-
Save guilhermepontes/17ae0cc71fa2b13ea8c20c94c5c35dc4 to your computer and use it in GitHub Desktop.
// original gist | |
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5); | |
// fully random by @BetonMAN | |
const shuffleArray = arr => arr | |
.map(a => [Math.random(), a]) | |
.sort((a, b) => a[0] - b[0]) | |
.map(a => a[1]); | |
shuffleArray([1, 2, 3]) //[3, 1, 2] |
In ES6 you can omit the closing parenthesis :)
But still its missing one ;)
ty guys!
What about objects?
Problem of this shuffle implementation is that it's not fully random. If you want really fully random shuffle, you need to use a code like this:
var array = [1,2,3,4,5,6,7,8,9];
var shuffled = array.map((a) => [Math.random(),a]).sort((a,b) => a[0]-b[0]).map((a) => a[1]);
For more information see this
@stamster wut?
@BetonMAN, neat implementation! It seems that the only downside, comparing to the implementation from Wikipedia, is that "the time and space complexity of the sort cannot be guaranteed as it is implementation dependent." MDN Array.sort . It is O(n) in the implementation of Fisher–Yates shuffle on Wikipedia .
Remember that the time complexity of sorting an array with length n is theta(n*log(n)), but the common shuffle algorithm takes theta(n). If the array is long, try to avoid sorting.
Thanks. Very useful snippet, but it's missing a final close parenthesis.