Last active
October 29, 2023 01:41
-
-
Save guilhermepontes/17ae0cc71fa2b13ea8c20c94c5c35dc4 to your computer and use it in GitHub Desktop.
Shuffle Array - JavaScript ES2015, ES6
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
// 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] |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 .