re: Write a simple but impactful script VIEW POST

re: Hey, this is nice. Can you please explain the function you passed to sort()?

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()).

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

code of conduct - report abuse