JavaScript
Article

jQuery output array in random order

By Sam Deering

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
Meet the author
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.

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the lastest in JavaScript, once a week, for free.