Skip to content

Instantly share code, notes, and snippets.

@snsxn
Forked from guilhermepontes/shuffle.js
Last active August 26, 2022 14:35
Show Gist options
  • Save snsxn/f548b88a10600840f74409cde97140d2 to your computer and use it in GitHub Desktop.
Save snsxn/f548b88a10600840f74409cde97140d2 to your computer and use it in GitHub Desktop.
3x one-liner 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]);
// 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