1const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
2
3console.log(shuffleArray([1, 2, 3, 4]));
4// Result: [ 1, 4, 3, 2 ]
5
1/**
2 * Shuffles array in place.
3 * @param {Array} a items An array containing the items.
4 */
5function shuffle(a) {
6 var j, x, i;
7 for (i = a.length - 1; i > 0; i--) {
8 j = round(random() * (i + 1));
9 x = a[i];
10 a[i] = a[j];
11 a[j] = x;
12 }
13 return a;
14}
15
16shuffle(array);
1/**
2 * Shuffles array in place.
3 * @param {Array} a items An array containing the items.
4 */
5function shuffle(a) {
6 var j, x, i;
7 for (i = a.length - 1; i > 0; i--) {
8 j = Math.floor(Math.random() * (i + 1));
9 x = a[i];
10 a[i] = a[j];
11 a[j] = x;
12 }
13 return a;
14}
15
16
17/**
18 * Shuffles array in place. ES6 version
19 * @param {Array} a items An array containing the items.
20 */
21function shuffle(a) {
22 for (let i = a.length - 1; i > 0; i--) {
23 const j = Math.floor(Math.random() * (i + 1));
24 [a[i], a[j]] = [a[j], a[i]];
25 }
26 return a;
27}
28
29var myArray = ['1','2','3','4','5','6','7','8','9'];
30shuffle(myArray);
1function shuffle(array) {
2 let currentIndex = array.length, randomIndex;
3
4 // While there remain elements to shuffle...
5 while (currentIndex != 0) {
6
7 // Pick a remaining element...
8 randomIndex = Math.floor(Math.random() * currentIndex);
9 currentIndex--;
10
11 // And swap it with the current element.
12 [array[currentIndex], array[randomIndex]] = [
13 array[randomIndex], array[currentIndex]];
14 }
15
16 return array;
17}
18
19// Used like so
20var arr = [2, 11, 37, 42];
21shuffle(arr);
22console.log(arr);