Array.prototype.shuffle = function() {
var original = this;
return { // Creates two sub-methods
new: function() {
/* Slower than Fisher-Yates algorithm but it
doesn't modify the original array. */
var shuffled = [], arrCopy = [], randomIndex;
original.forEach(function(item){ arrCopy.push(item); });
while (arrCopy.length) {
randomIndex = (arrCopy.length > 1) ?
getRandom(arrCopy.length - 1) : 0;
shuffled.push(arrCopy.splice(randomIndex, 1)[0]);
} // End of shuffling
return shuffled;
}, // Creates a new shuffled copy
original: function() {
// Created by Ronald A. Fisher and Frank Yates.
var counter = original.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter -= 1;
temp = original[counter];
original[counter] = original[index];
original[index] = temp;
} // End of shuffling
/* Comment out the following line if
you wanted a side-effect instead */
return original;
} // Shuffles the original array
}; // End of returning two sub-methods
}; // End of Shuffle method
// THIS METHOD OF THE ARRAY PROPERTY WILL SHUFFLE ITS CONTENTS (RANDOM ORDER)
// AND YOU HAVE TWO WAYS OF DOING IT, MY WAY THAT CREATES A COPY OF THE
// ORIGINAL ARRAY, AND THE FISHER-YATES ALGORITHM THAT TAKES EFFECT ON THE
// ORIGINAL ARRAY (A SIDE EFFECT) MAKING IT FASTER.
var arr = [1, 2, 3, 4, 5, 6, 7];
arr.shuffle.original();
console.log(arr); // Outputs -> [4, 7, 1, 3, 2, 6, 5] for example
Helper function shuffle the contents of an array ─ This snippet is a piece of a JavaScript library I'm working on, you can see it here: https://github.com/luishendrix92/WindowbirdJS
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.