2

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.

JetBrains
  • 456
  • 2
  • 6
  • 18
Erich Schmidt
  • 31
  • 1
  • 3

1 Answers1

6

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
}
JetBrains
  • 456
  • 2
  • 6
  • 18
  • The "sort using Math.raondom" *is not very random!* The sorting algorithm will try to minimise the swaps and use the past results of the comparer function. Since you're just providing an unstable compare function, you are getting slightly randomised results but not very. – VLAZ Nov 20 '20 at 07:58
  • 1
    I dont think it's a good idea to use sort with a compareFunc that generates random results. It should be better to do something like `points.map(p => ({ p, i: Math.random}).sort((a, b) => a.i - b.i).map(p => p.p);` – hansmaad Nov 20 '20 at 07:59
  • 1
    Warning! The use of this algorithm is not recommended, because it is inefficient and strongly biased; see comments. It is being left here for future reference, because the idea is not that rare. – adir abargil Nov 20 '20 at 08:00