Skip to content

Instantly share code, notes, and snippets.

@guilhermepontes
Last active October 29, 2023 01:41
Show Gist options
  • Save guilhermepontes/17ae0cc71fa2b13ea8c20c94c5c35dc4 to your computer and use it in GitHub Desktop.
Save guilhermepontes/17ae0cc71fa2b13ea8c20c94c5c35dc4 to your computer and use it in GitHub Desktop.
Shuffle Array - JavaScript ES2015, ES6
// 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]
@guilhermepontes
Copy link
Author

@stamster wut?

@tigco
Copy link

tigco commented Apr 8, 2018

@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 .

@Aqua-Dream
Copy link

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