re: Write a simple but impactful script VIEW POST

re: Just wanted to share my script :p Array.from(Array(1001).keys()) .map(number => number.toString().padStart(4, '0')) .sort(number => n... Comment marked as low quality/non-constructive by the community View code of conduct

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

Sure, we were supposed to sort randomly and sort() expects a function that compares two values and returns >0 if greater 0 if equal and <0 if lesser, so,

• For the random order, I used Math.random that returns a value between 0 and 1

• To be sure that it can return a negative number I multiplied the random times number * 2 so:

• If Math.random < 0.5 it will be positive
• If Math.random == 0.5 it will be zero
• If Math.random > 0.5 it will be negative

However, since we have three possible cases it could be better to do something like:

.sort(number => number - Math.floor(Math.random() * number * 3));

That way there is a 33.33% of probability for each case.

code of conduct - report abuse  