jQuery output array in random order

Sam Deering
Tweet

Just some sharing of some jQuery snippets to display/sort things in random order.

Sort Code Snippets

Use this function in object literal format.

shuffleAds: function(arr)
{
  for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
  return arr;
}

View Demo

Another function to do the same thing.

function randsort(c) {
    var o = new Array();
    for (var i = 0; i < c; i++) {
        var n = Math.floor(Math.random()*c);
        if( jQuery.inArray(n, o) > 0 ) --i;
        else o.push(n);
    }
    return o;
}

Also thought this jQuery Shuffle plugin was worth including.

/*
 * jQuery shuffle
 *
 * Copyright (c) 2008 Ca-Phun Ung <caphun at yelotofu dot com>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://yelotofu.com/labs/jquery/snippets/shuffle/
 *
 * Shuffles an array or the children of a element container.
 * This uses the Fisher-Yates shuffle algorithm <http: //jsfromhell.com/array/shuffle [v1.0]>
 */

(function($){

    $.fn.shuffle = function() {
        return this.each(function(){
            var items = $(this).children().clone(true);
            return (items.length) ? $(this).html($.shuffle(items)) : this;
        });
    }

    $.shuffle = function(arr) {
        for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
        return arr;
    }

})(jQuery);

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments