Shuffling JavaScript array values
This tip comes from John Howard’s 12 Extremely Useful Hacks for JavaScript article.
If you ever need to randomly sort an array of items in JavaScript, here’s a simple function to help you do so:
var shuffle = function (arr) {
// Create a clone of the array so that we don't shuffle the original one
var arrClone = arr.slice(0);
// Shuffle the array
return arrClone.sort(function() {
return Math.random() - 0.5
})
}
To use it, pass in any array.
var flavors = ['chocolate', 'vanilla', 'coffee', 'strawberry'];
var shuffledFlavors = shuffle( flavors );
// ex. return ["coffee", "vanilla", "strawberry", "chocolate"]