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.

3
  • What do you mean with random sort? Do you mean Bogosort or random shuffle? Commented Nov 20, 2020 at 7:52
  • yes I mean something as random shuffle Commented Nov 20, 2020 at 7:57
  • You may try this one Commented Nov 20, 2020 at 8:02

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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);
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.