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?
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?
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]
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/