Skip to content
Advertisement

JQuery object shuffle / randomize

Hi I have a JQuery object with multiple divs inside each containing text:

var object = $(<div>我</div>,<div>喜欢</div>,<div>吃</div>);

I want to copy the object and shuffle the divs inside so that when I display the new object, it will be a shuffled version of the original object. Is this possible with a JQuery object or am I going to have to store the divs in an array, and if so can someone tell me how I could achieve this?

Advertisement

Answer

Use a generic shuffle algorithm (e.g. the Fisher-Yates shuffle) and pass your object as the argument, e.g.

function shuffle(array) {
  var m = array.length, t, i;
    
  // While there remain elements to shuffle…
  while (m) {
    
    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);
    
    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
    
  return array;
};
    
 
var object = $('<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div>');
    
/* use spread operator to pass the array of divs */
var shuffledArray = shuffle([...object]);

/* append divs to the body */
$('body').html($(shuffledArray));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Advertisement