Skip to main content Skip to secondary navigation 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) {
    return arr.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"]

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

Get Daily Developer Tips