Today I Learned - Rocky Kev

TIL randomize Arrays

POSTED ON:

TAGS:

A one line helper function to randomize array items.

let arr = [1, 2, 3];

sortRandom(arr);
// arr = [3, 2, 1]

sortRandom(arr);
// arr = [2, 1, 3]

sortRandom(arr);
// arr = [3, 1, 2]


const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)

How it works

That somewhat works, because Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.

NOTE: Not all permutations have the same probability.

To test, https://javascript.info/task/shuffle did a test looping that process a million times, and counting the results.

123: 250706 // WOAH
132: 124425
213: 249618 // WOAH
231: 124880
312: 125148
321: 125223

There are some other ways to do it, that are a bit longer of code to do better randomization.
But for your basic needs, this will do just fine.

The Better but longer way

function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
123: 166693
132: 166647
213: 166628
231: 167517
312: 166199
321: 166316

REFERENCE:
Via this: https://javascript.plainenglish.io/15-helpful-javascript-one-liners-946e1d1a1653
which pointed to this:
https://javascript.info/task/shuffle


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.