Shortest Form (Using Lambda Expression):
To answer the question "How sorting of an array in random order works", as others have mentioned, the Array.sort() function can take a function as parameter.
Syntax:
Array.sort([sort_by_function()])
The inner sort_by_function()
accepts two parameters (e.g.: x & y) and with use of Math.random()
returns a value between -0.5 to 0.5, it returns:
- Negative number (-0.5 to -0.1), if x < y
- Zero (0), if x = y Positive
- Positive number (0.1 to 0.5), if x > y
Remember, if you don't pass in anything to the outer Array.sort()
function, it simply rearranges/sorts the elements in Ascending order, if however, you pass in a function (as argument), then it behaves based on what the inner sort_by_function()
returns, as it swaps EACH Element of the given array (by swapping pair of two elements at-a-time) essentially, this swapping is decided based on what the inner sort_by_function()
returned.
To achieve random-sort order the Array.sort()
function will rearrange/sort each pair of elements as below, for a:
- Negative value: swap in ascending order,
- Zero: no change,
- Positive value: swap in descending order.
Example:
arr.sort(function(x,y){return Math.random() - 0.5});
As no one mentioned about the use of the short Lambda expression, here is an example on how you can shorten the inner parameter-function by use of the Lambda expression as below:
arr.sort(() => Math.random() - 0.5);