Skip to content

Instantly share code, notes, and snippets.

@guilhermepontes
Last active October 29, 2023 01:41
Show Gist options
  • Star 65 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • 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]
@oosmos
Copy link

oosmos commented Aug 10, 2017

Thanks. Very useful snippet, but it's missing a final close parenthesis.

@KokoDoko
Copy link

In ES6 you can omit the closing parenthesis :)

@DutchKevv
Copy link

But still its missing one ;)

@guilhermepontes
Copy link
Author

ty guys!

@stamster
Copy link

What about objects?

@BetonMAN
Copy link

BetonMAN commented Nov 29, 2017

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

@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