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 
 * 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 
 */

(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);

Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


No Reader comments

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.