Skip to main content Accessibility Feedback

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"]

🔥 Hot off the press! I just launched a new pocket guide. Learn how to build interactive web apps with vanilla JavaScript.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips