Skip to content

Instantly share code, notes, and snippets.

@jabney
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jabney/018feaa6b115b386260e to your computer and use it in GitHub Desktop.
Save jabney/018feaa6b115b386260e to your computer and use it in GitHub Desktop.
Shuffle an array in place so that the positions of its values are random
// shuffle.js © 2014 James Abney http://github.com/jabney
(function(ex) {
'use strict';
// Export shuffle to 'random' namespace.
var random = ex.random || (ex.random = Object.create(null));
// Shuffle an array in place so that the positions of its values are random.
random.shuffle = function shuffle(a) {
var i, r, tmp, len = a.length;
for (i = 0; i < len; i++) {
r = i + Math.floor((len - i) * Math.random());
tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
return a;
}
})(typeof exports !== 'undefined' && exports || this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment