jQuery: randomize and shuffle an array

Finally I've found a very useful script that actually randomizes/shuffles an array, so I decided to implement a $.randomize() global jQuery method to accomplish this task. It soon turned out that the aforementioned script works well especially when we deal with jQuery DOM node lists turned into arrays using get(). The implementation of this method is as follows:

(function($) {

  $.randomize = 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;


A simple test with an unordered list:

$(function() {

  $('#run').click(function(event) {
    var $li = $('li', '#test').get();
    var random = $.randomize($li);


You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: randomize and shuffle an array”

Leave a Reply

Note: Only a member of this blog may post a comment.