0

guess I have a list with the next:

20 22 24

how can I sort the three elements randomly so I get stuff like 22, 20, 24 or 24,20,22?

I know you can generate random numbers but I think I'm not looking for that?

user2304057
  • 113
  • 4
  • 8
  • Related: http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array – RAS Jun 14 '13 at 22:39

2 Answers2

3

You'll need to implement a shuffle algorithm, for example

var arr = [20, 22, 24];

function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
    if(a.length === 0) return a;
    var i = a.length, t, j;
    a = a.slice();
    while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
    return a;
}

shuffleArray(arr); // [22, 24, 20]
shuffleArray(arr); // [22, 20, 24]
shuffleArray(arr); // [24, 22, 20]
Petrov
  • 4,200
  • 6
  • 40
  • 61
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Nice, it worked. Whenever Stack Overflow allows me, I'll rate your answer as best. – user2304057 Jun 14 '13 at 22:48
  • Great. If you want side effects you can comment out/remove `a = a.slice();`, and if thereafter you don't need a return either, the same to `return a;`. It would speed up slightly but destroy the original _Array's_ order. – Paul S. Jun 14 '13 at 22:51
  • careful ! this function creates an infinite loop if a = []... Corrected in the response. – Petrov Apr 17 '20 at 00:41
0

Somewhat simpler than the other options if you don't mind the original array being modified:

function randomizeArray(arr) {
    var output = [];
    while (arr.length) {
        output.push(arr.splice(Math.floor(Math.random() * arr.length), 1)[0]);
    }
    return output;
}

This cycles through the original array and selects a random index each time, then adds the element at that index to the destination array and removes it from the original array. Then, repeat process until original array is empty.

Working demo here: http://jsfiddle.net/jfriend00/7jhs7/

jfriend00
  • 683,504
  • 96
  • 985
  • 979