I had learned about the sort method, but got stuck at the random sorting part.
I know we can use this:
array.sort (function(a, b) {
return 0.5 - Math.random()});
to create a random sorted array, but how does it work?
This is what I know so far:
array.sort(function(a, b){return a - b});
it will sort the array from small number to bigger number,
it’s because the value which a - b returns is negative, so the smaller number will be in the front.
vice versa,
array.sort(function(a, b){return b - a});
the value which b - a returns is positive, so the bigger number will be in the front.
But here comes the question,
Math.random() can create number between 0~1 (excluded),
which means the result of 0.5 - Math.random() could be either a positive or negative value.
Then, why it can create many different arrays instead of just ascending and descending one?
for example, this array [40,100,10,5,1,25]
how does it become like [100,40,5,1,10,25] or [5,40,1,100,25,10] by using the method of Math.random?