DEV Community

Discussion on: Write a simple but impactful script

Collapse
 
kyserrecchia profile image
kyserrecchia • Edited

I hope you don't mind me answering on Pichardo's behalf (or Pichardo).

Sort iterates over consecutive pairs through the array and takes their differences. If a negative value returns, it knows the previous value comes before it, if positive, then after, and it sorts the array accordingly. But we don't want that to happen here as we're dealing with strings, e.g. we don't want the string, "39" to come after the string, "220" but alphabetically, they ought to just like "alphabet" comes before "bat". Since sort only knows what to do based on the sign it receives, if we pass the two indices as parameters to a function and have it do their difference numerically, it sorts everything as expected. And since we don't actually want a sort in this case, but want things random, if we only pass the first of the two indices of each pair and compare it to a random value, we get things randomly "sorted".

An even simpler way to achieve the same result would be to just do .sort(number=>.5 - Math.random()).

Thread Thread
 
pichardoj profile image
J. Pichardo

That's right 0.5 - Math.random() would've worked as well