-
-
Save snsxn/f548b88a10600840f74409cde97140d2 to your computer and use it in GitHub Desktop.
3x one-liner 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]); | |
// Fisher-Yates shuffle one-liner | |
const shuffleArray = (arr) => [...Array(arr.length)].map((_, i) => Math.floor(Math.random() * (i + 1))).reduce((shuffled, r, i) => shuffled.map((num, j) => j === i ? shuffled[r] : j === r ? shuffled[i] : num),arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment