var array = [3,9,23,76,1,54,21,12,0,9,2];
var shuffled = array.sort(function() {return 0.5 - Math.random()});
console.log(shuffled);
I'm aware of the results, and also satified with them.
The code above returns a shuffled order of the elements of my array.
I'm puzzled by why it results in that output.
What's the point of the function inside of the .sort
and how does it contribute to the output?
I think the purpose of the sort is to randomly arrange the items in the list. The anonymous function to the sort() method is either going to return a positive or negative value, which is precisely what the callback is supposed to do.
The sort callback is supposed to be used to compare two items, and return either -1, 0, or -1 for less than, equality, and greater than, respectively.
Now there's probably another discussion about whether that is a good way to randomize, because the comparing function could return different values for the same two objects on discrete calls.....
The function actually takes two arguments, which are 2 items from the array. The purpose is to compare these elements and return a number.
If the number is positive, the second item should be before the first item.
If the number is 0 or negative, the second item should be after the first item.
In each case of the example above,
a === 0
andb === 1
.Edit for step by step output
To see step-by-step what is happening with an ascending sort on
[1,3,2,4,4,0]
, one can write a function which logs exactly what happens each stepwhich outputs
For completeness, probability table for shuffle algorithm in original question (estimates, based on 500,000 trials for each index), X is starting index
The argument to
sort
is a sorting callback, it is a function that supposed to take two values being sorted as arguments and return negative, 0, or positive depending if first value compared is lesser, equal, or greater than second.In your particular example, this callback completely ignores actual values compared and instead generates a random number with
Math.random
, that returns a value in range 0 .. 1 and subtracts it from 0.5 to change resulting range to -0.5 .. 0.5. This makes sort randomly assume one value being lesser or greater than another and ends in generating list shuffled randomly instead of sorted by some "real" condition.