Sorting an Array in Random Order
You used
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
And here the most important thing is as.sort(func)
.func(a,b)
will return value in range of [-0.5,0.5]
.
Because this function return 0.5 - Math.random()
and Math.random()
will return the float value which is in range of [0,1]
.
So that your func
will return value in range of [-0.5,0.5]
.
And this mean that sort order will be set increase
or decrease
.
this is random.
So your result will be random
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return Math.random();
}
console.log(s);
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0 - Math.random();
}
console.log(s);
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
Math.random()
returns a number between 0
and 1
(exclusive). We're using 0.5
because it is the mean value.
Array.sort()
sorts the parameters based on the return value. So, 0.5 - Math.random()
will yield either positive or negative value with equal probability. Hence, it will sort the parameters randomly.
How it really works
- If the return value of
Array.sort()
is positive, then the index of the first parameter will be higher than that of the second. - If it is negative, then the index of the second parameter will be higher than that of the first.
- And, if it is
0
, then do nothing.
Math.random() return random value between 0 to 1 (0 is included but 1 is excluded). So 0.5 act as mid point. If use use value like greater than 1 or less 0 than it will always be either true or false. So for this reason 0.5 is used.
You can read more here about Math.random()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Let's understand it bit more with examples
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
console.log(s);
This is what you get when you use value greater than 1
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return 1 - Math.random();
}
console.log(s);
This is what happens when you use value less than 0
var as = ["max","jack","sam"];
var s = as.sort(func);
function func(a, b) {
return -1 - Math.random();
}
console.log(s);
P.S :-
Try printing output from all the above condition you will see that last two condition will always return either true or false from function. so you will not get a random sorting.
Now talk about any value from 0 to 0.99 you can use any value but 0.5 will serve your purpose best.Because it's a middle point you're most likely to get best answer.