1

I'm going through javascript.info and doing the practice tasks for Array Methods. This one is "Shuffle an array" and the instructions are:

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array.

I couldn't figure it out so I looked it up but now im struggling to understand it. What does the ".5 -" do in the line .5 - Math.random?

let arr = [1, 2, 3];

function shuffle(array) {
    return arr.sort((a, b) => .5 - Math.random())
}
console.log(shuffle(arr))
wraytheon
  • 29
  • 5

1 Answers1

2

The .sort callback will iterate over the elements of the array and sort them depending on the value returned by the callback. If a negative number is returned, a will be sorted before b - if a positive number is returned, b will be sorted before a.

Math.random() returns a number between 0 and 1. If it's subtracted from 0.5, you get a random number between -0.5 and +0.5. So doing

(a, b) => .5 - Math.random()

is a way to get the callback to return a positive number 50% of the time and a negative number 50% of the time, and will randomly shuffle the array to a certain extent.

That said, "sorting" in this manner will produce biased results. Use a better algorithm.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I see. Thank you for taking the time to help me out! So if I were to do `(a, b) => .25 - Math.random()` this would return a positive number 75% of the time, returning the same 3 digit sequence pattern 75% of the time, correct? (I understand this isn't helpful for my use case). I tested it in JSFiddle and this seems to be the case, as it returned [1, 2, 3] about 75% of the time. – wraytheon Aug 03 '22 at 18:36