panrosmithe
panrosmithe

Reputation: 69

Shuffling an array: Why does this work?

I'm in the process of making a JavaScript solitaire game. I was looking for info on how to use sort() and Math.random() together in order to shuffle the deck when I happened upon this on CSS tricks:

array.sort(function() {return 0.5 - Math.random()})

Works beautifully, which is awesome, but I have no idea why. Would someone explain why this works?

Upvotes: 0

Views: 217

Answers (1)

amateur_me
amateur_me

Reputation: 55

How Array.sort works

In sort function, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

array.sort(function(a, b){return a - b});

Now, if (a-b) is less than 0, a is sorted to an index lower than b, as a is lesser than b.

If (a-b) returns 0, leave a and b unchanged with respect to each other, as they are equal. Note: the ECMAscript standard does not guarantee this behaviour.

If (a-b) is greater than 0, b is sorted to an index lower than a, as a is greater than b.

How Math.Random works

It just returns a random value between 0 and 1.

Now coming to this case, since the actual values in the array are ignored here, and a random value is passed to (a-b) the function will just randomly return < 0, 0 or > 0 for every pair that gets compared. Hence the different sort order for same array.

Upvotes: 1

Related Questions