Given the following arr:
const arr = ['Jane', 'Kelvin', 'Gabriel', 'Bob', 'Alex'];
If I use the
sort method to sort an array, I know the order of the elements will be rearranged based on alphabetic order in case the elements are strings;
console.log(arr.sort()); // output: Alex, Bob, Gabriel, Jane, Kelvin
If the elements are numbers:
const arrNumbers = [20, 1, 17, 30, 28]; console.log(arrNumbers.sort()); // output: 1, 17, 20, 28, 30
I have a solid understanding of how the
sort method works, and I can see it’s not completely random, that’s why people would use the following code:
arr.sort(() => 0.5 - Math.random());
With the above code the
arr will be rearranged randomly and problem solved, but what’s the logic here? I’d like to know what’s going on and not just use a code blindly, but I don’t understand this part
0.5 - Math.random()
Math.random() returns any number from 0 to 0.99999… but why subtract 0.5 from it?
Thanks in advance.