Hi I have a JQuery object with multiple divs inside each containing text:
JavaScript
x
2
1
var object = $(<div>我</div>,<div>喜欢</div>,<div>吃</div>);
2
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.
JavaScript
1
26
26
1
function shuffle(array) {
2
var m = array.length, t, i;
3
4
// While there remain elements to shuffle…
5
while (m) {
6
7
// Pick a remaining element…
8
i = Math.floor(Math.random() * m--);
9
10
// And swap it with the current element.
11
t = array[m];
12
array[m] = array[i];
13
array[i] = t;
14
}
15
16
return array;
17
};
18
19
20
var object = $('<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div>');
21
22
/* use spread operator to pass the array of divs */
23
var shuffledArray = shuffle([object]);
24
25
/* append divs to the body */
26
$('body').html($(shuffledArray));
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>