how can I sort an array randomly in javascript?
I have tried this:
array.sort(function(a, b){return Math.random()});
but it doesn't work.
how can I sort an array randomly in javascript?
I have tried this:
array.sort(function(a, b){return Math.random()});
but it doesn't work.
First of all, You're welcome to stackoverflow!
You can look at this question: Sorting an Array in Random Order
You can sort an array in a random order by providing a custom compare function:
var points = [1, 2, 3, 4, 5];
points.sort(function(a, b){return 0.5 - Math.random()});
But the above example is not accurate, it will favor some numbers over the others.
The most popular correct method, is the Fisher Yates shuffle:
var points = [40, 100, 1, 5, 25, 10];
for (i = points.length -1; i > 0; i--) {
j = Math.floor(Math.random() * i)
k = points[i]
points[i] = points[j]
points[j] = k
}