Skip to content

Instantly share code, notes, and snippets.

@frantorreg
Last active April 25, 2017 00:08
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 frantorreg/4d52be8ce6c630d6e1807dbfb528d0cd to your computer and use it in GitHub Desktop.
Save frantorreg/4d52be8ce6c630d6e1807dbfb528d0cd to your computer and use it in GitHub Desktop.
Disorder a JavaScript array

#1 Overwriting the original array

var array = [1, 2, 3, 4]
// [1, 2, 3, 4]
array.disorder()
// [2, 4, 1, 3]
array
// [2, 4, 1, 3]

#2 Keeping the original array

var array = [1, 2, 3, 4]
// [1, 2, 3, 4]
array.disorder(true)
// [2, 4, 1, 3]
array
// [1, 2, 3, 4]
/**
* Disorder the array
*
* @param {bool} preserve Returns a copy without modifying the original
* @return {array} The disordered array
*/
Array.prototype.disorder = function (preserve) {
var array = preserve ? this.slice() : this;
var disordered = [];
while(array.length > 0) {
var index = Math.round(Math.random()*(array.length-1));
disordered.push(array[index]);
array.splice(index, 1);
}
if(!preserve) {
Array.prototype.push.apply(this, disordered);
}
return disordered;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment