jeudi 25 février 2021

Why sort() using Math.random() is different from using a number?

I have two different results using the same range of numbers. Sorry if it is obvius, I am a total beginner and couldn't find the answer for this.

This below shuffles the array.

(function(array) {
    array.sort(() => 0.5 - Math.random());
    console.log(array);
})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// Output: [Shuffled array]

However, if I manually write a random number between -0.5 and 0.5, I can't shuffle it. Why??

(function(array) {
    array.sort(() => 0.2145467);
    console.log(array);
})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]



Aucun commentaire:

Enregistrer un commentaire